daily pastebin goal
17%
SHARE
TWEET

game of life finally working

a guest Jun 24th, 2018 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import random
  2. import pygame as pg
  3. import copy
  4.  
  5. pg.init()
  6. screen = pg.display.set_mode((300, 300))
  7. clock = pg.time.Clock()
  8.  
  9. grid_size = 100
  10. old_grid = [[0 for x in range(grid_size)] for y in range(grid_size)]
  11.  
  12. for i in range(0, grid_size):
  13.     for j in range(0, grid_size):
  14.         old_grid[i][j] = random.randrange(0, 2)
  15. new_grid = copy.deepcopy(old_grid)
  16.  
  17. def cell_block(x, y, state):
  18.     cell_size = 3
  19.     pg.draw.rect(screen, (255, 255, 255) if state == 1 else (0, 0, 0), (x * cell_size, y * cell_size, cell_size, cell_size))
  20.  
  21. def wrapindex(i):
  22.     return (i % grid_size + grid_size) % grid_size
  23.  
  24. running = True
  25. while running:
  26.     screen.fill((0, 0, 0))
  27.     clock.tick(60)
  28.     for event in pg.event.get():
  29.         if event.type == pg.QUIT:
  30.             running = False
  31.     for x in range(len(old_grid)):
  32.         for y in range(len(old_grid[x])):
  33.             neighbors = old_grid[wrapindex(x - 1)][wrapindex(y - 1)] + old_grid[wrapindex(x)][wrapindex(y - 1)] + old_grid[wrapindex(x + 1)][wrapindex(y - 1)] + \
  34.                         old_grid[wrapindex(x - 1)][wrapindex(y)]     +                        0                       + old_grid[wrapindex(x + 1)][wrapindex(y)] + \
  35.                         old_grid[wrapindex(x - 1)][wrapindex(y + 1)] + old_grid[wrapindex(x)][wrapindex(y + 1)] + old_grid[wrapindex(x + 1)][wrapindex(y + 1)]
  36.  
  37.             if neighbors == 3:
  38.                 new_grid[x][y] = 1
  39.             elif neighbors > 3:
  40.                 new_grid[x][y] = 0
  41.             elif neighbors < 2:
  42.                 new_grid[x][y] = 0
  43.  
  44.             cell_block(x, y, new_grid[x][y])
  45.  
  46.     pg.display.flip()
  47.     old_grid = copy.deepcopy(new_grid)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top