Write me a snake game in python and pygame
- User
Write me a snake game in python and pygame
- Assistant
Write me a snake game in python and pygame
Sure! Here's a simple Snake game implemented in Python using Pygame. This game allows you to control a snake to eat food, grow longer, and avoid colliding with walls or itself.
import pygame
import sys
import time
import random
# Initialize Pygame
pygame.init()
# Set up the game window dimensions
window_x = 720
window_y = 480
# Create the game window
pygame.display.set_caption('Snake Game')
game_window = pygame.display.set_mode((window_x, window_y))
# Define colors (R, G, B)
black = pygame.Color(0, 0, 0) # Background
white = pygame.Color(255, 255, 255) # Food
red = pygame.Color(255, 0, 0) # Game Over text
green = pygame.Color(0, 255, 0) # Snake
blue = pygame.Color(50, 153, 213) # Score
# Frames per second controller
fps_controller = pygame.time.Clock()
# Define snake default position and body
snake_pos = [100, 50] # [x, y]
snake_body = [[100, 50],
[90, 50],
[80, 50],
[70, 50]]
# Fruit position
fruit_pos = [random.randrange(1, (window_x // 10)) * 10,
random.randrange(1, (window_y // 10)) * 10]
fruit_spawn = True
# Set default direction
direction = 'RIGHT'
change_to = direction
# Initialize score
score = 0
# Function to display score
def show_score(choice, color, font, size):
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Score : ' + str(score), True, color)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.topleft = (10, 10)
else:
score_rect.center = (window_x / 2, window_y / 1.5)
game_window.blit(score_surface, score_rect)
# Function to end the game
def game_over():
my_font = pygame.font.SysFont('times new roman', 50)
game_over_surface = my_font.render('Game Over!', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.center = (window_x / 2, window_y / 4)
game_window.fill(black)
game_window.blit(game_over_surface, game_over_rect)
show_score(0, red, 'times new roman', 30)
pygame.display.flip()
time.sleep(2)
pygame.quit()
sys.exit()
# Main logic
while True:
# Handling key events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# When a key is pressed
elif event.type == pygame.KEYDOWN:
if event.key in [pygame.K_UP, ord('w')]:
change_to = 'UP'
elif event.key in [pygame.K_DOWN, ord('s')]:
change_to = 'DOWN'
elif event.key in [pygame.K_LEFT, ord('a')]:
change_to = 'LEFT'
elif event.key in [pygame.K_RIGHT, ord('d')]:
change_to = 'RIGHT'
# Validate direction changes (no 180-degree turns)
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
elif change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
elif change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
elif change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Update snake position [x, y]
if direction == 'UP':
snake_pos[1] -= 10
elif direction == 'DOWN':
snake_pos[1] += 10
elif direction == 'LEFT':
snake_pos[0] -= 10
elif direction == 'RIGHT':
snake_pos[0] += 10
# Snake body growing mechanism
snake_body.insert(0, list(snake_pos))
# If the snake eats the fruit
if snake_pos == fruit_pos:
score += 10
fruit_spawn = False
else:
snake_body.pop() # Remove last segment
# Spawn a new fruit
if not fruit_spawn:
fruit_pos = [random.randrange(1, (window_x // 10)) * 10,
random.randrange(1, (window_y // 10)) * 10]
fruit_spawn = True
# Clear the screen and draw the snake and fruit
game_window.fill(black)
for pos in snake_body:
pygame.draw.rect(game_window, green,
pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(game_window, white,
pygame.Rect(fruit_pos[0], fruit_pos[1], 10, 10))
# Check for collisions with the boundaries
if (snake_pos[0] < 0 or snake_pos[0] > window_x - 10 or
snake_pos[1] < 0 or snake_pos[1] > window_y - 10):
game_over()
# Check for collisions with itself
for block in snake_body[1:]:
if snake_pos == block:
game_over()
# Display the score
show_score(1, blue, 'times new roman', 20)
# Refresh game screen
pygame.display.update()
# Control the speed of the snake
fps_controller.tick(15)
Install Python 3: Ensure that Python 3 is installed on your system. You can download it from the official website.
Install Pygame: If you haven't installed Pygame, open your terminal or command prompt and run:
pip install pygame
Save the Code: Copy the code above and save it in a file named snake_game.py.
Run the Game: In your terminal or command prompt, navigate to the directory where snake_game.py is saved and execute:
python snake_game.py
WSADYou can customize the game by modifying the following:
fps_controller.tick(15) line. Increasing the number will make the snake move faster.window_x and window_y to adjust the game window dimensions.Enjoy coding and playing your own Snake game!
Not yet included in a published release.