Below is an example of a simple Snake game written in Python using the Pygame library. You can copy the code into a file (for example, snake_game.py) and run it. If you don’t have Pygame installed, install it with:
pip install pygame
Once you have Pygame installed, here is the full code:
import pygame
import time
import random
# Initialize pygame
pygame.init()
# Define colors (RGB)
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# Display settings
display_width = 600
display_height = 400
# Create display
game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Snake Game")
# Clock for controlling the snake speed
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15 # Adjust this value for faster/slower snake
# Fonts for text rendering
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
def our_snake(snake_block, snake_list):
"""
Draws each block of the snake onto the screen.
"""
for x in snake_list:
pygame.draw.rect(game_display, green, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
"""
Displays a message on the game window.
"""
mesg = font_style.render(msg, True, color)
game_display.blit(mesg, [display_width / 6, display_height / 3])
def game_loop():
"""
Main game loop.
"""
game_over = False
game_close = False
# Starting position of the snake (center of the display)
x1 = display_width / 2
y1 = display_height / 2
# Initial movement direction
x1_change = 0
y1_change = 0
# List to keep track of snake segments
snake_list = []
length_of_snake = 1
# Create first food block
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
while not game_over:
# When game_close is True, the game is over and waiting for user input
while game_close:
game_display.fill(black)
message("You lost! Press Q-Quit or C-Play Again", red)
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() # Restart the game
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# Handle keystrokes for directions
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
# Check for boundaries - if snake goes off screen
if x1 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:
game_close = True
# Update snake head coordinates
x1 += x1_change
y1 += y1_change
game_display.fill(black)
# Draw the food on the screen
pygame.draw.rect(game_display, blue, [foodx, foody, snake_block, snake_block])
# Define the new head for the snake
snake_head = [x1, y1]
snake_list.append(snake_head)
# If the snake becomes longer than its allowed length, remove the tail segment
if len(snake_list) > length_of_snake:
del snake_list[0]
# If the snake collides with itself, then end the game
for segment in snake_list[:-1]:
if segment == snake_head:
game_close = True
# Draw the snake
our_snake(snake_block, snake_list)
pygame.display.update()
# Check if snake eats the food
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
if __name__ == "__main__":
game_loop()
How the Code Works
-
Initialization:
- The code begins by importing necessary modules and initializing Pygame.
- Colors, display size, snake block size, and clock settings are defined.
-
Drawing the Snake:
- The
our_snake function iterates over the list of snake segments and draws each rectangle to represent the snake.
-
Game Loop:
- The
game_loop() function contains the main game logic that handles events, updates the snake position, checks collisions (with the screen boundaries and the snake’s own body), places the food, and handles game-over states.
- When the snake eats the food (i.e., its head's coordinates match the food's coordinates), the snake grows (increased length), and a new food location is randomly generated.
-
Game Over State:
- When the snake collides with the boundaries or itself, a game-over message is displayed. The player can press Q to quit or C to restart the game.
-
Main:
- The script starts the game by calling
game_loop() inside the if __name__ == "__main__": block.
Enjoy playing and feel free to enhance the game (for example, by tracking and displaying scores, adding sound effects, or improving graphics)!