Sure! Here's an example code that runs Conway's Game of Life using Tkinter:
import tkinter as tk
import random
# Define the size of the grid
grid_size = 30
# Define the size of each cell
cell_size = 20
# Initialize the grid
grid = [[random.choice([0, 1]) for _ in range(grid_size)] for _ in range(grid_size)]
def update_grid():
global grid
# Create a new grid to store the updated state
new_grid = [[0] * grid_size for _ in range(grid_size)]
for i in range(grid_size):
for j in range(grid_size):
# Count the number of live neighbors
live_neighbors = 0
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
ni = (i + dx) % grid_size
nj = (j + dy) % grid_size
live_neighbors += grid[ni][nj]
# Apply the rules of the game
if grid[i][j] == 1:
if live_neighbors < 2 or live_neighbors > 3:
new_grid[i][j] = 0
else:
new_grid[i][j] = 1
else:
if live_neighbors == 3:
new_grid[i][j] = 1
# Update the grid
grid = new_grid
# Redraw the grid
draw_grid()
def draw_grid():
canvas.delete("all")
for i in range(grid_size):
for j in range(grid_size):
x = j * cell_size
y = i * cell_size
if grid[i][j] == 1:
canvas.create_rectangle(x, y, x + cell_size, y + cell_size, fill="black")
else:
canvas.create_rectangle(x, y, x + cell_size, y + cell_size, fill="white")
# Schedule the next update
canvas.after(100, update_grid)
# Create the tkinter window
window = tk.Tk()
window.title("Conway's Game of Life")
# Create the canvas to draw the grid
canvas = tk.Canvas(window, width=grid_size * cell_size, height=grid_size * cell_size)
canvas.pack()
# Start the game
update_grid()
# Run the tkinter event loop
window.mainloop()
This code initializes a random grid of cells and updates their state according to the rules of Conway's Game of Life. The grid is displayed using a Tkinter canvas, and the game is updated every 100 milliseconds. You can modify the grid_size and cell_size variables to change the size of the grid and the cells.