Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_conways_game_of_life.py
- import random
- import time
- from tkinter import *
- CELL_SIZE = 4
- GRID_WIDTH = 120 # Adjusted for 500px canvas
- GRID_HEIGHT = 120
- WINDOW_WIDTH = GRID_WIDTH * CELL_SIZE
- WINDOW_HEIGHT = GRID_HEIGHT * CELL_SIZE
- FONT = ('Times New Roman', 16, "bold")
- def num_neighbors(grid, x, y):
- neighbors = 0
- for dx in [-1, 0, 1]:
- for dy in [-1, 0, 1]:
- if dx == 0 and dy == 0:
- continue
- nx, ny = x + dx, y + dy
- if 0 <= nx < GRID_HEIGHT and 0 <= ny < GRID_WIDTH:
- neighbors += grid[nx][ny]
- return neighbors
- def update_state(grid):
- new_grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
- live_cells = []
- for x in range(GRID_HEIGHT):
- for y in range(GRID_WIDTH):
- n = num_neighbors(grid, x, y)
- cell = grid[x][y]
- if cell == 1 and (n == 2 or n == 3):
- new_grid[x][y] = 1
- live_cells.append((x, y))
- elif cell == 0 and n == 3:
- new_grid[x][y] = 1
- live_cells.append((x, y))
- return new_grid, live_cells
- def draw_grid(canvas, live_cells):
- canvas.delete('all')
- for x, y in live_cells:
- canvas.create_text(y * CELL_SIZE + 10, x * CELL_SIZE + 10, text='.', font=FONT, fill='white')
- canvas.update()
- root = Tk()
- root.title("Conway's Game of Life")
- canvas = Canvas(root, bg='blue', height=WINDOW_HEIGHT, width=WINDOW_WIDTH)
- canvas.pack()
- total_cells = GRID_WIDTH * GRID_HEIGHT
- lives = [0] * int(total_cells * 0.9) + [1] * int(total_cells * 0.1)
- random.shuffle(lives)
- grid = [[lives.pop() for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
- while True:
- grid, live_cells = update_state(grid)
- draw_grid(canvas, live_cells)
Advertisement
Add Comment
Please, Sign In to add comment