Advertisement
here2share

# Tk_conways_game_of_life.py

Sep 3rd, 2020
1,828
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. # Tk_conways_game_of_life.py
  2.  
  3. import random
  4. from Tkinter import *
  5.  
  6. def num_neighbors(grid, pos):
  7.     neighbors = 0
  8.     x,y = pos
  9.  
  10.     neighbors += grid[x-1][y-1] # Top Left
  11.     neighbors += grid[x-1][y]   # Top
  12.     neighbors += grid[x-1][y+1] # Top Right
  13.  
  14.     neighbors += grid[x][y-1]   # Left
  15.     neighbors += grid[x][y+1]   # Right
  16.  
  17.     neighbors += grid[x+1][y-1] # Bottom Left
  18.     neighbors += grid[x+1][y]   # Bottom
  19.     neighbors += grid[x+1][y+1] # Bottom Right
  20.                
  21.     return neighbors
  22.  
  23.  
  24. def update_state(grid):
  25.     global xy
  26.     crowded = len(xy) > 1600
  27.     # print len(xy)
  28.     xy = []
  29.     h, w = len(grid)-1, len(grid[0])-1
  30.     new_grid = eval(str([[0]*(w+1)]*(h+1)))
  31.  
  32.     for x in range(h):
  33.         for y in range(w):
  34.             n = num_neighbors(grid, [x,y])
  35.             cell = grid[x][y]
  36.             t = 0
  37.             if crowded and cell:
  38.                 if n > 3 or n < 2:
  39.                     new_grid[x][y] = 0
  40.                 else:
  41.                     t = 1
  42.             elif cell == 0 and n == 3:
  43.                 t = 1
  44.             elif cell == 1 and n < 4:
  45.                 t = 1
  46.             if t:
  47.                 new_grid[x][y] = 1
  48.                 xy.append((x,y))
  49.  
  50.     return new_grid
  51.  
  52.  
  53. def print_grid():
  54.     for x,y in xy:
  55.         canvas.create_text(x*4+10,y*4+10,text='.', font=fff)
  56.     canvas.update()
  57.     canvas.delete('all')
  58.  
  59. fff = ('Times New Roman', 16, "bold")
  60. if 1:
  61.     ww = 500
  62.     hh = 500
  63.     xy = []
  64.     lives = [0]*int((ww*hh/4)*0.9)+[1]*int((ww*hh/4)*0.2)
  65.     random.shuffle(lives)
  66.     grid = [[lives.pop() for x in range(ww/4-3)] for y in range(hh/4-4)]
  67.     root = Tk()
  68.     canvas = Canvas(root, bg='blue', height=hh, width=ww)
  69.     canvas.pack()
  70.  
  71.     while 1:
  72.         print_grid()
  73.         grid = update_state(grid)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement