Sure! Here's a simple implementation of Conway's Game of Life using tkinter in Python:
import tkinter as tk
import random
# Constants
WIDTH = 600
HEIGHT = 600
CELL_SIZE = 10
# Create the main window
root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
# Initialize the grid
grid = [[0] * (WIDTH // CELL_SIZE) for _ in range(HEIGHT // CELL_SIZE)]
# Function to draw the grid on the canvas
def draw_grid():
for i in range(HEIGHT // CELL_SIZE):
for j in range(WIDTH // CELL_SIZE):
x1, y1 = j * CELL_SIZE, i * CELL_SIZE
x2, y2 = (j + 1) * CELL_SIZE, (i + 1) * CELL_SIZE
if grid[i][j] == 1:
color = "black"
else:
color = "white"
canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline="black")
# Function to update the grid according to the rules of the Game of Life
def update_grid():
new_grid = [[0] * (WIDTH // CELL_SIZE) for _ in range(HEIGHT // CELL_SIZE)]
for i in range(HEIGHT // CELL_SIZE):
for j in range(WIDTH // CELL_SIZE):
neighbors = count_neighbors(i, j)
if grid[i][j] == 1:
if neighbors < 2 or neighbors > 3:
new_grid[i][j] = 0
else:
new_grid[i][j] = 1
elif grid[i][j] == 0:
if neighbors == 3:
new_grid[i][j] = 1
else:
new_grid[i][j] = 0
global grid
grid = new_grid
# Function to count the number of live neighbors for a given cell
def count_neighbors(i, j):
count = 0
for di in range(-1, 2):
for dj in range(-1, 2):
if di == 0 and dj == 0:
continue
ni, nj = i + di, j + dj
if 0 <= ni < HEIGHT // CELL_SIZE and 0 <= nj < WIDTH // CELL_SIZE:
count += grid[ni][nj]
return count
# Initialize the grid with random live cells
for i in range(HEIGHT // CELL_SIZE):
for j in range(WIDTH // CELL_SIZE):
grid[i][j] = random.choice([0, 1])
# Create a loop that updates and draws the grid every 100ms
def mainloop():
update_grid()
draw_grid()
root.after(100, mainloop)
# Start the main loop
mainloop()
root.mainloop()
This code will create a 600x600 pixel canvas with a grid of cells that are 10x10 pixels each. The grid is initialized with random live cells, and then the mainloop function is called repeatedly to update and draw the grid every 100ms. The update function uses the count_neighbors function to count the number of live neighbors for each cell in the grid, and then updates the grid according to the rules of the Game of Life. The draw_grid function is used to draw the updated grid on the canvas.
I hope this helps! Let me know if you have any questions.