Advertisement
Guest User

Untitled

a guest
Feb 5th, 2016
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.90 KB | None | 0 0
  1. import std.stdio : write, writeln;
  2. import std.conv;
  3. import std.random : uniform;
  4.  
  5. immutable int WORLD_SIZE_X = 80, WORLD_SIZE_Y = 24, FILL_PERCENT = 45,
  6.               NUM_GENS = 6;
  7.  
  8. int main()
  9. {
  10.     int[WORLD_SIZE_Y][WORLD_SIZE_X] world;
  11.     writeln("Generation 0:");
  12.     initialise(world);
  13.     display(world);
  14.     for (int i = 0; i < NUM_GENS; i++)
  15.     {
  16.         writeln("Generation " ~ to!string(i + 1) ~ ":");
  17.         world = nextGen(world);
  18.         display(world);
  19.     }
  20.     return 0;
  21. }
  22.  
  23. // fills world with random values
  24. void initialise(ref int[WORLD_SIZE_Y][WORLD_SIZE_X] world)
  25. {
  26.     for (int x = 0; x < WORLD_SIZE_X; x++)
  27.     {
  28.         for (int y = 0; y < WORLD_SIZE_Y; y++)
  29.         {
  30.             world[x][y] = uniform(0, 100) > (100 - FILL_PERCENT) ? 1 : 0;
  31.         }
  32.     }
  33. }
  34.  
  35. // displays the world
  36. void display(ref int[WORLD_SIZE_Y][WORLD_SIZE_X] world)
  37. {
  38.     for (int y = 0; y < WORLD_SIZE_Y; y++)
  39.     {
  40.         for (int x = 0; x < WORLD_SIZE_X; x++)
  41.         {
  42.             switch (world[x][y])
  43.             {
  44.                 case 0: write(" "); break;
  45.                 case 1: write("▓"); break;
  46.                 default: break;
  47.             }
  48.         }
  49.         write("\n");
  50.     }
  51. }
  52.  
  53. // counts the number of walls in a size*size square centred on the point x,y
  54. int countsq(int size, int x, int y, int[WORLD_SIZE_Y][WORLD_SIZE_X] world)
  55. {
  56.     int count = 0;
  57.     for (int i = -(size/2); i <= (size/2); i++)
  58.     {
  59.         int offsetx = x - i;
  60.         for (int j = -(size/2); j <= (size/2); j++)
  61.         {
  62.             int offsety = y - j;
  63.             if (offsetx < 0 || offsetx >= WORLD_SIZE_X || offsety < 0
  64.                 || offsety >= WORLD_SIZE_Y)
  65.             {
  66.                 count += 1;
  67.             }
  68.             else
  69.             {
  70.                 count += world[offsetx][offsety];
  71.             }
  72.         }
  73.     }
  74.     return count;
  75. }
  76.  
  77. int[WORLD_SIZE_Y][WORLD_SIZE_X] nextGen(int[WORLD_SIZE_Y][WORLD_SIZE_X] oldGen)
  78. {
  79.     int[WORLD_SIZE_Y][WORLD_SIZE_X] output;
  80.     for (int x = 0; x < WORLD_SIZE_X; x++)
  81.     {
  82.         for (int y = 0; y < WORLD_SIZE_Y; y++)
  83.         {
  84.             int count = countsq(3, x, y, oldGen);
  85.             output[x][y] = count > 4 ? 1 : 0;
  86.         }
  87.     }
  88.    
  89.     return output;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement