o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
code snake game in python 3.9
- User
code snake game in python 3.9
- Assistant
code snake game in python 3.9
Sure! Below is a simple implementation of the classic Snake game using Python 3.9 and the Pygame library. Before running the code, make sure you have Pygame installed. You can install it using:
pip install pygame
Here's the code:
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Set up the display
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 400
CELL_SIZE = 20
DISPLAY = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Snake Game')
# Set up the clock for controlling the frame rate
FPS = 10
clock = pygame.time.Clock()
# Define colors
BLACK = pygame.Color(0, 0, 0) # Background
WHITE = pygame.Color(255, 255, 255) # Unused, but can be for text
GREEN = pygame.Color(0, 255, 0) # Snake
RED = pygame.Color(255, 0, 0) # Food
# Define the snake's initial position and body
snake_pos = [100, 50]
snake_body = [
[100, 50],
[80, 50],
[60, 50]
]
# Define the food's initial position
food_pos = [
random.randrange(1, (WINDOW_WIDTH // CELL_SIZE)) * CELL_SIZE,
random.randrange(1, (WINDOW_HEIGHT // CELL_SIZE)) * CELL_SIZE
]
food_spawn = True
# Set the initial direction of the snake
direction = 'RIGHT'
change_to = direction
# Initialize score
score = 0
# Set up fonts
font_style = pygame.font.SysFont('arial', 35)
# Game Over function
def game_over():
game_over_surface = font_style.render(f'Your Score: {score}', True, RED)
game_over_rect = game_over_surface.get_rect()
game_over_rect.center = (WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)
DISPLAY.blit(game_over_surface, game_over_rect)
pygame.display.flip()
# Pause for 2 seconds
pygame.time.sleep(2)
pygame.quit()
sys.exit()
# Main game loop
while True:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == ord('w'):
if direction != 'DOWN':
change_to = 'UP'
elif event.key == pygame.K_DOWN or event.key == ord('s'):
if direction != 'UP':
change_to = 'DOWN'
elif event.key == pygame.K_LEFT or event.key == ord('a'):
if direction != 'RIGHT':
change_to = 'LEFT'
elif event.key == pygame.K_RIGHT or event.key == ord('d'):
if direction != 'LEFT':
change_to = 'RIGHT'
# Update the direction
direction = change_to
# Update the snake's position
if direction == 'UP':
snake_pos[1] -= CELL_SIZE
elif direction == 'DOWN':
snake_pos[1] += CELL_SIZE
elif direction == 'LEFT':
snake_pos[0] -= CELL_SIZE
elif direction == 'RIGHT':
snake_pos[0] += CELL_SIZE
# Snake body growing mechanism
snake_body.insert(0, list(snake_pos))
if snake_pos == food_pos:
score += 1
FPS += 0.5 # Increase speed each time the snake eats food
food_spawn = False
else:
snake_body.pop()
# Spawn food on the screen
if not food_spawn:
food_pos = [
random.randrange(1, (WINDOW_WIDTH // CELL_SIZE)) * CELL_SIZE,
random.randrange(1, (WINDOW_HEIGHT // CELL_SIZE)) * CELL_SIZE
]
food_spawn = True
# Clear the screen
DISPLAY.fill(BLACK)
# Draw the snake
for block in snake_body:
pygame.draw.rect(DISPLAY, GREEN, pygame.Rect(block[0], block[1], CELL_SIZE, CELL_SIZE))
# Draw the food
pygame.draw.rect(DISPLAY, RED, pygame.Rect(food_pos[0], food_pos[1], CELL_SIZE, CELL_SIZE))
# Check for collisions with the boundaries
if (snake_pos[0] < 0 or snake_pos[0] >= WINDOW_WIDTH or
snake_pos[1] < 0 or snake_pos[1] >= WINDOW_HEIGHT):
game_over()
# Check for collisions with itself
for block in snake_body[1:]:
if snake_pos == block:
game_over()
# Update the display
pygame.display.update()
# Control the frame rate
clock.tick(FPS)
Instructions to run the game:
Install Pygame (if you haven't already):
pip install pygame
Save the code above into a file named snake_game.py.
Run the game from your command line or terminal:
python snake_game.py
Controls:
Game Rules:
Customization:
Feel free to enhance the game by adding features such as:
Enjoy your game!