Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_conways_game_of_life.py
- import random
- from Tkinter import *
- def num_neighbors(grid, pos):
- neighbors = 0
- x,y = pos
- neighbors += grid[x-1][y-1] # Top Left
- neighbors += grid[x-1][y] # Top
- neighbors += grid[x-1][y+1] # Top Right
- neighbors += grid[x][y-1] # Left
- neighbors += grid[x][y+1] # Right
- neighbors += grid[x+1][y-1] # Bottom Left
- neighbors += grid[x+1][y] # Bottom
- neighbors += grid[x+1][y+1] # Bottom Right
- return neighbors
- def update_state(grid):
- global xy
- crowded = len(xy) > 1600
- # print len(xy)
- xy = []
- h, w = len(grid)-1, len(grid[0])-1
- new_grid = eval(str([[0]*(w+1)]*(h+1)))
- for x in range(h):
- for y in range(w):
- n = num_neighbors(grid, [x,y])
- cell = grid[x][y]
- t = 0
- if crowded and cell:
- if n > 3 or n < 2:
- new_grid[x][y] = 0
- else:
- t = 1
- elif cell == 0 and n == 3:
- t = 1
- elif cell == 1 and n < 4:
- t = 1
- if t:
- new_grid[x][y] = 1
- xy.append((x,y))
- return new_grid
- def print_grid():
- for x,y in xy:
- canvas.create_text(x*4+10,y*4+10,text='.', font=fff)
- canvas.update()
- canvas.delete('all')
- fff = ('Times New Roman', 16, "bold")
- if 1:
- ww = 500
- hh = 500
- xy = []
- lives = [0]*int((ww*hh/4)*0.9)+[1]*int((ww*hh/4)*0.2)
- random.shuffle(lives)
- grid = [[lives.pop() for x in range(ww/4-3)] for y in range(hh/4-4)]
- root = Tk()
- canvas = Canvas(root, bg='blue', height=hh, width=ww)
- canvas.pack()
- while 1:
- print_grid()
- grid = update_state(grid)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement