Here's a simple implementation of the classic Snake Game written in Python using the popular pygame library. You can copy, run, and play it!
Snake Game Code
import pygame
import time
import random
# Initialize pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 600, 400
# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
# Set up the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# Clock for controlling the game's speed
clock = pygame.time.Clock()
# Snake block size
block_size = 10
# Font styles
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
def display_score(score):
"""Display the current score on the screen."""
value = score_font.render("Your Score: " + str(score), True, WHITE)
screen.blit(value, [0, 0])
def draw_snake(block_size, snake_list):
"""Draw the snake on the screen."""
for x in snake_list:
pygame.draw.rect(screen, GREEN, [x[0], x[1], block_size, block_size])
def display_message(msg, color):
"""Display a centered message on the screen."""
message = font_style.render(msg, True, color)
screen.blit(message, [WIDTH / 6, HEIGHT / 3])
def game_loop():
"""Main game loop."""
# Game over flag
game_over = False
game_close = False
# Initial position of the snake
x1 = WIDTH / 2
y1 = HEIGHT / 2
# Changes in position
x1_change = 0
y1_change = 0
# Snake details
snake_list = []
snake_length = 1
# Position of food
food_x = round(random.randrange(0, WIDTH - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, HEIGHT - block_size) / 10.0) * 10.0
# Main game loop
while not game_over:
while game_close:
screen.fill(BLACK)
display_message("You lost! Press Q-Quit or C-Play Again", RED)
display_score(snake_length - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if x1_change == 0: # Prevent reversing direction
x1_change = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
if x1_change == 0:
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
if y1_change == 0:
y1_change = -block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
if y1_change == 0:
y1_change = block_size
x1_change = 0
# Check boundaries
if x1 >= WIDTH or x1 < 0 or y1 >= HEIGHT or y1 < 0:
game_close = True
# Snake moves
x1 += x1_change
y1 += y1_change
screen.fill(BLACK)
# Draw food
pygame.draw.rect(screen, BLUE, [food_x, food_y, block_size, block_size])
# Update snake's body
snake_head = [x1, y1]
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# Check if the snake collides with itself
for block in snake_list[:-1]:
if block == snake_head:
game_close = True
draw_snake(block_size, snake_list)
display_score(snake_length - 1)
pygame.display.update()
# Check if the snake eats the food
if x1 == food_x and y1 == food_y:
food_x = round(random.randrange(0, WIDTH - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, HEIGHT - block_size) / 10.0) * 10.0
snake_length += 1
# Control the speed of the game
clock.tick(15)
pygame.quit()
quit()
# Run the game
game_loop()
Instructions to Run:
- Make sure you have Python installed on your system (3.x version works best).
- Install the
pygame library if you don’t already have it:
pip install pygame
- Copy the code into a file, for example,
snake_game.py.
- Run the game:
python snake_game.py
- Use the arrow keys (
UP, DOWN, LEFT, RIGHT) to control the snake.
- Try to eat the blue food and avoid colliding with the walls (or yourself)!
Features:
- Displays the current score.
- Restart the game by pressing
C.
- Quit the game by pressing
Q.
Let me know if you need help modifying or expanding this game! 🐍🎮