here2share

# tk_conways_game_of_life.py

Sep 3rd, 2020 (edited)
2,010
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. # tk_conways_game_of_life.py
  2.  
  3. import random
  4. import time
  5. from tkinter import *
  6.  
  7. CELL_SIZE = 4
  8. GRID_WIDTH = 120  # Adjusted for 500px canvas
  9. GRID_HEIGHT = 120
  10. WINDOW_WIDTH = GRID_WIDTH * CELL_SIZE
  11. WINDOW_HEIGHT = GRID_HEIGHT * CELL_SIZE
  12. FONT = ('Times New Roman', 16, "bold")
  13.  
  14. def num_neighbors(grid, x, y):
  15.     neighbors = 0
  16.     for dx in [-1, 0, 1]:
  17.         for dy in [-1, 0, 1]:
  18.             if dx == 0 and dy == 0:
  19.                 continue
  20.             nx, ny = x + dx, y + dy
  21.             if 0 <= nx < GRID_HEIGHT and 0 <= ny < GRID_WIDTH:
  22.                 neighbors += grid[nx][ny]
  23.     return neighbors
  24.  
  25. def update_state(grid):
  26.     new_grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
  27.     live_cells = []
  28.  
  29.     for x in range(GRID_HEIGHT):
  30.         for y in range(GRID_WIDTH):
  31.             n = num_neighbors(grid, x, y)
  32.             cell = grid[x][y]
  33.             if cell == 1 and (n == 2 or n == 3):
  34.                 new_grid[x][y] = 1
  35.                 live_cells.append((x, y))
  36.             elif cell == 0 and n == 3:
  37.                 new_grid[x][y] = 1
  38.                 live_cells.append((x, y))
  39.     return new_grid, live_cells
  40.  
  41. def draw_grid(canvas, live_cells):
  42.     canvas.delete('all')
  43.     for x, y in live_cells:
  44.         canvas.create_text(y * CELL_SIZE + 10, x * CELL_SIZE + 10, text='.', font=FONT, fill='white')
  45.     canvas.update()
  46.  
  47. root = Tk()
  48. root.title("Conway's Game of Life")
  49. canvas = Canvas(root, bg='blue', height=WINDOW_HEIGHT, width=WINDOW_WIDTH)
  50. canvas.pack()
  51.  
  52. total_cells = GRID_WIDTH * GRID_HEIGHT
  53. lives = [0] * int(total_cells * 0.9) + [1] * int(total_cells * 0.1)
  54. random.shuffle(lives)
  55. grid = [[lives.pop() for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
  56.  
  57. while True:
  58.     grid, live_cells = update_state(grid)
  59.     draw_grid(canvas, live_cells)
Advertisement
Add Comment
Please, Sign In to add comment