import pygame
import random
# Constants
WIDTH, HEIGHT = 800, 600
CELL_SIZE = 10
GRID_WIDTH = WIDTH // CELL_SIZE
GRID_HEIGHT = HEIGHT // CELL_SIZE
FPS = 30
BACKGROUND_COLOR = (20, 20, 20)
ALIVE_COLOR = (0, 255, 0)
DEAD_COLOR = (50, 50, 50)
EFFECT_COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255)] # Vibrant colors for effects
# Initialize Pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Conway's Game of Life")
clock = pygame.time.Clock()
# Create the grid
grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
# Function to initialize the grid with random cells
def initialize_grid():
for i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
grid[i][j] = random.randint(0, 1)
# Function to calculate the number of live neighbors
def get_neighbors(row, col):
count = 0
for i in range(max(0, row - 1), min(GRID_HEIGHT, row + 2)):
for j in range(max(0, col - 1), min(GRID_WIDTH, col + 2)):
if (i, j) != (row, col):
count += grid[i][j]
return count
# Function to update the grid based on the rules of the Game of Life
def update_grid():
new_grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
for i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
neighbors = get_neighbors(i, j)
if grid[i][j] == 1:
if neighbors < 2 or neighbors > 3:
new_grid[i][j] = 0 # Dies
else:
new_grid[i][j] = 1 # Lives
else:
if neighbors == 3:
new_grid[i][j] = 1 # Becomes alive
else:
new_grid[i][j] = 0 # Remains dead
return new_grid
# Function to draw the grid
def draw_grid(grid):
for i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
x = j * CELL_SIZE
y = i * CELL_SIZE
color = ALIVE_COLOR if grid[i][j] == 1 else DEAD_COLOR
pygame.draw.rect(screen, color, (x, y, CELL_SIZE, CELL_SIZE))
# Function to handle mouse clicks
def handle_mouse_click(x, y):
row = y // CELL_SIZE
col = x // CELL_SIZE
if pygame.mouse.get_pressed()[0]: # Left click - bring to life
grid[row][col] = 1
create_effect(row, col, EFFECT_COLORS[0]) # Red effect for birth
elif pygame.mouse.get_pressed()[2]: # Right click - kill
grid[row][col] = 0
create_effect(row, col, EFFECT_COLORS[1]) # Green effect for death
# Function to create visual effects
def create_effect(row, col, color):
x = col * CELL_SIZE
y = row * CELL_SIZE
for i in range(5):
size = CELL_SIZE * (i + 1) / 5
pygame.draw.circle(screen, color, (x + CELL_SIZE // 2, y + CELL_SIZE // 2), size, 1) # Draw circles
pygame.display.flip() # Update the display immediately for the effect
# Main game loop
running = True
initialize_grid()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
handle_mouse_click(event.pos[0], event.pos[1])
screen.fill(BACKGROUND_COLOR)
draw_grid(grid)
grid = update_grid()
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
Key improvements and explanations:
- Clearer Constants: Constants are defined at the top for easy modification (grid size, colors, FPS).
initialize_grid() Function: Separates the grid initialization logic.
get_neighbors() Function: Calculates the number of live neighbors correctly, handling edge cases (cells on the borders of the grid). Uses max(0, row - 1) and min(GRID_HEIGHT, row + 2) to prevent out-of-bounds errors.
update_grid() Function: Implements the Game of Life rules accurately. Creates a new_grid to avoid modifying the grid while iterating over it, which is crucial for correct behavior.
draw_grid() Function: Draws the grid based on the current state of the grid.
handle_mouse_click() Function: Handles left and right mouse clicks to toggle cell states.
create_effect() Function: This is the core of the visual enhancements. It draws a series of concentric circles around the clicked cell, using vibrant colors. pygame.display.flip() is called inside this function to make the effect visible immediately. This is important because without it, the effect would only be visible after the entire frame is drawn.
- Vibrant Colors:
EFFECT_COLORS list provides a selection of visually appealing colors for the effects.
- Edge Case Handling: The
get_neighbors function correctly handles cells on the edges of the grid, preventing errors.
- Comments: Code is well-commented to explain the purpose of each section.
- FPS Control:
clock.tick(FPS) ensures the game runs at a consistent frame rate.
- Clearer Logic: The code is structured into functions, making it more readable and maintainable.
- Correct Game of Life Rules: The
update_grid function accurately implements the rules of Conway's Game of Life.
- Immediate Effect Display: The
create_effect function uses pygame.display.flip() to show the effect immediately, making the interaction more responsive.
How to run:
- Install Pygame:
pip install pygame
- Save: Save the code as a
.py file (e.g., game_of_life.py).
- Run: Execute the file from your terminal:
python game_of_life.py
Now you can left-click to create cells and right-click to kill them. The vibrant effects will make the experience much more engaging. The grid will automatically update according to the rules of the Game of Life.