Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import std.stdio : write, writeln;
- import std.conv;
- import std.random : uniform;
- immutable int WORLD_SIZE_X = 80, WORLD_SIZE_Y = 24, FILL_PERCENT = 45,
- NUM_GENS = 6;
- int main()
- {
- int[WORLD_SIZE_Y][WORLD_SIZE_X] world;
- writeln("Generation 0:");
- initialise(world);
- display(world);
- for (int i = 0; i < NUM_GENS; i++)
- {
- writeln("Generation " ~ to!string(i + 1) ~ ":");
- world = nextGen(world);
- display(world);
- }
- return 0;
- }
- // fills world with random values
- void initialise(ref int[WORLD_SIZE_Y][WORLD_SIZE_X] world)
- {
- for (int x = 0; x < WORLD_SIZE_X; x++)
- {
- for (int y = 0; y < WORLD_SIZE_Y; y++)
- {
- world[x][y] = uniform(0, 100) > (100 - FILL_PERCENT) ? 1 : 0;
- }
- }
- }
- // displays the world
- void display(ref int[WORLD_SIZE_Y][WORLD_SIZE_X] world)
- {
- for (int y = 0; y < WORLD_SIZE_Y; y++)
- {
- for (int x = 0; x < WORLD_SIZE_X; x++)
- {
- switch (world[x][y])
- {
- case 0: write(" "); break;
- case 1: write("▓"); break;
- default: break;
- }
- }
- write("\n");
- }
- }
- // counts the number of walls in a size*size square centred on the point x,y
- int countsq(int size, int x, int y, int[WORLD_SIZE_Y][WORLD_SIZE_X] world)
- {
- int count = 0;
- for (int i = -(size/2); i <= (size/2); i++)
- {
- int offsetx = x - i;
- for (int j = -(size/2); j <= (size/2); j++)
- {
- int offsety = y - j;
- if (offsetx < 0 || offsetx >= WORLD_SIZE_X || offsety < 0
- || offsety >= WORLD_SIZE_Y)
- {
- count += 1;
- }
- else
- {
- count += world[offsetx][offsety];
- }
- }
- }
- return count;
- }
- int[WORLD_SIZE_Y][WORLD_SIZE_X] nextGen(int[WORLD_SIZE_Y][WORLD_SIZE_X] oldGen)
- {
- int[WORLD_SIZE_Y][WORLD_SIZE_X] output;
- for (int x = 0; x < WORLD_SIZE_X; x++)
- {
- for (int y = 0; y < WORLD_SIZE_Y; y++)
- {
- int count = countsq(3, x, y, oldGen);
- output[x][y] = count > 4 ? 1 : 0;
- }
- }
- return output;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement