make a snake game
- User
make a snake game
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
make a snake game
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure! I'd be happy to help you create a classic Snake game using Python. We'll use the Pygame library, which is a popular choice for developing games in Python.
Overview:
Let's get started!
First, make sure you have Pygame installed. You can install it using pip:
pip install pygame
Create a new Python file (e.g., snake_game.py) and import the required modules.
import pygame
import sys
import random
import time
# Initialize Pygame
pygame.init()
# Set up the game window
window_width = 600
window_height = 400
game_window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')
We'll define some colors using RGB values for easy reference.
# Colors (R, G, B)
black = pygame.Color(0, 0, 0) # Background
white = pygame.Color(255, 255, 255) # Score text
red = pygame.Color(255, 0, 0) # Game Over text
green = pygame.Color(0, 255, 0) # Snake
blue = pygame.Color(0, 0, 255) # Food
This will control the game's frame rate.
# FPS (frames per second) controller
fps_controller = pygame.time.Clock()
# Snake parameters
snake_position = [100, 50] # Starting position [x, y]
snake_body = [ # Initial snake body segments
[100, 50],
[90, 50],
[80, 50]
]
# Food position
food_position = [random.randrange(1, (window_width // 10)) * 10,
random.randrange(1, (window_height // 10)) * 10]
food_spawn = True
# Direction controls
direction = 'RIGHT'
change_to = direction
# Score
score = 0
def show_score(choice=1):
font = pygame.font.SysFont('arial', 24)
score_surface = font.render('Score: ' + str(score), True, white)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.topleft = (10, 10)
else:
score_rect.center = (window_width // 2, window_height // 1.5)
game_window.blit(score_surface, score_rect)
This function will display a message when the game ends.
def game_over():
font = pygame.font.SysFont('arial', 72)
game_over_surface = font.render('Game Over', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (window_width // 2, window_height // 4)
game_window.blit(game_over_surface, game_over_rect)
show_score(0)
pygame.display.flip()
time.sleep(3)
pygame.quit()
sys.exit()
Now, we'll create the main logic of the game inside a while loop.
# Main logic
while True:
# Handling 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'
elif event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# Validate direction
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Update snake position
if direction == 'UP':
snake_position[1] -= 10
if direction == 'DOWN':
snake_position[1] += 10
if direction == 'LEFT':
snake_position[0] -= 10
if direction == 'RIGHT':
snake_position[0] += 10
# Snake body growing mechanism
snake_body.insert(0, list(snake_position))
if snake_position == food_position:
score += 1
food_spawn = False
else:
snake_body.pop()
# Spawn new food
if not food_spawn:
food_position = [random.randrange(1, (window_width // 10)) * 10,
random.randrange(1, (window_height // 10)) * 10]
food_spawn = True
# Clear screen
game_window.fill(black)
# Draw Snake
for pos in snake_body:
pygame.draw.rect(game_window, green, pygame.Rect(
pos[0], pos[1], 10, 10))
# Draw Food
pygame.draw.rect(game_window, blue, pygame.Rect(
food_position[0], food_position[1], 10, 10))
# Check for collisions
# Wall collision
if (snake_position[0] < 0 or snake_position[0] > window_width - 10 or
snake_position[1] < 0 or snake_position[1] > window_height - 10):
game_over()
# Self collision
for block in snake_body[1:]:
if snake_position == block:
game_over()
# Show score
show_score()
# Refresh game screen
pygame.display.update()
# Control game speed
fps_controller.tick(15)
Make sure the game runs when you execute the script.
Here's the complete code for the snake game:
import pygame
import sys
import random
import time
# Initialize Pygame
pygame.init()
# Set up the game window
window_width = 600
window_height = 400
game_window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')
# Colors (R, G, B)
black = pygame.Color(0, 0, 0) # Background
white = pygame.Color(255, 255, 255) # Score text
red = pygame.Color(255, 0, 0) # Game Over text
green = pygame.Color(0, 255, 0) # Snake
blue = pygame.Color(0, 0, 255) # Food
# FPS controller
fps_controller = pygame.time.Clock()
# Game variables
snake_position = [100, 50]
snake_body = [
[100, 50],
[90, 50],
[80, 50]
]
food_position = [random.randrange(1, (window_width // 10)) * 10,
random.randrange(1, (window_height // 10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
# Functions
def show_score(choice=1):
font = pygame.font.SysFont('arial', 24)
score_surface = font.render('Score: ' + str(score), True, white)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.topleft = (10, 10)
else:
score_rect.center = (window_width // 2, window_height // 1.5)
game_window.blit(score_surface, score_rect)
def game_over():
font = pygame.font.SysFont('arial', 72)
game_over_surface = font.render('Game Over', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (window_width // 2, window_height // 4)
game_window.blit(game_over_surface, game_over_rect)
show_score(0)
pygame.display.flip()
time.sleep(3)
pygame.quit()
sys.exit()
# Main logic
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Control inputs
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'
elif event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# Update direction
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Move snake
if direction == 'UP':
snake_position[1] -= 10
if direction == 'DOWN':
snake_position[1] += 10
if direction == 'LEFT':
snake_position[0] -= 10
if direction == 'RIGHT':
snake_position[0] += 10
# Snake growing mechanism
snake_body.insert(0, list(snake_position))
if snake_position == food_position:
score += 1
food_spawn = False
else:
snake_body.pop()
# Food spawn
if not food_spawn:
food_position = [random.randrange(1, (window_width // 10)) * 10,
random.randrange(1, (window_height // 10)) * 10]
food_spawn = True
# Clear screen
game_window.fill(black)
# Draw snake
for pos in snake_body:
pygame.draw.rect(game_window, green, pygame.Rect(
pos[0], pos[1], 10, 10))
# Draw food
pygame.draw.rect(game_window, blue, pygame.Rect(
food_position[0], food_position[1], 10, 10))
# Check for collisions
if (snake_position[0] < 0 or snake_position[0] > window_width - 10 or
snake_position[1] < 0 or snake_position[1] > window_height - 10):
game_over()
for block in snake_body[1:]:
if snake_position == block:
game_over()
# Display score
show_score()
# Refresh screen
pygame.display.update()
# Control speed
fps_controller.tick(15)
Ensure Python and Pygame are Installed:
pip install pygame.Save the Script:
snake_game.py.Run the Game:
snake_game.py.python snake_game.py.Controls:
Game Initialization:
Game Variables:
snake_position keeps track of the head of the snake.snake_body is a list of positions that make up the snake.food_position is randomly generated within the window confines.direction and change_to handle the movement mechanics.score tracks the player's score.Event Handling:
Game Logic:
Rendering:
Game Over:
Frame Rate Control:
fps_controller.tick(15) to set the game's speed.Change Game Speed:
fps_controller.tick() value to make the game faster or slower.Increase Difficulty:
Enhance Graphics:
Implement a Restart Mechanism:
game_over() function to allow the player to restart without closing the game.Feel free to experiment with the code to add new features or improve the game's design. Happy coding!
Not yet included in a published release.