Creating a Snake Game in Python. The Classic Snake game is a fun project to get started with Python Programming and game development in Python using Pygame Library. In this tutorial, we’ll walk through the process of building a simple Snake game step by step.
Table of Contents
Setting Up Pygame
First, ensure you have Pygame installed. If not install it by using pip-
pip install pygame
Next, import the necessary modules-
import pygame
import sys # Used for system-specific parameters and functions
import random # Used for generating random numbers
import time # Used for handling time-related tasks
Initialize Pygame and Create the Game Window
Initialize Pygame and set the game window
pygame.init() # Initialize all imported Pygame modules
size = (500, 500) # Set the size of the window (width, height)
display = pygame.display.set_mode(size) # Create the window
pygame.display.set_caption('Snake Game') # Set the window title
Define Colors and Game Variables
Define colors and initial snake game variables
# Colors in RGB format
black = (0, 0, 0)
white = (255, 255, 255)
red = (213, 50, 80)
green = (0, 255, 0)
# Snake block size
block_size = 10
# Initial snake position and body
snake_pos = [100, 50] # The initial position of the snake's head
snake_body = [[100, 50], [90, 50], [80, 50]] # The initial positions of the snake's body segments
# Initial food position
food_pos = [random.randrange(1, (size[0] // 10)) * 10, random.randrange(1, (size[1] // 10)) * 10]
food_spawn = True # A flag to check if the food is spawned on the screen
# Initial direction
direction = 'RIGHT' # The initial direction of the snake's movement
change_to = direction # Variable to store the new direction
# Initial score
score = 0 # Variable to keep track of the score
Helper functions for Snake Game
Create functions to handle turning, collisions, score display, and game over.
def turn_snake(direction, change_to):
"""
This function changes the direction of the snake based on the player's input.
"""
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
elif change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
elif change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
elif change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
return direction
def collision_with_bounds(snake_pos):
"""
This function checks if the snake has collided with the boundaries of the window.
"""
if snake_pos[0] >= size[0] or snake_pos[0] < 0 or snake_pos[1] >= size[1] or snake_pos[1] < 0:
return True
return False
def collision_with_self(snake_body):
"""
This function checks if the snake has collided with itself.
"""
for block in snake_body[1:]:
if snake_pos == block:
return True
return False
def show_score(choice, color, font, font_size):
"""
This function displays the score on the screen.
"""
score_font = pygame.font.SysFont(font, font_size) # Define the font and size
score_surface = score_font.render('Score : ' + str(score), True, color) # Render the score text
score_rect = score_surface.get_rect() # Get the rectangle for positioning
if choice == 1:
score_rect.midtop = (size[0] / 10, 15) # Position the score at the top left
else:
score_rect.midtop = (size[0] / 2, size[1] / 1.25) # Position the score at the center bottom
display.blit(score_surface, score_rect) # Display the score on the screen
def game_over():
"""
This function handles the game over scenario.
"""
my_font = pygame.font.SysFont('times new roman', 50) # Define the font and size
game_over_surface = my_font.render('Your Score is : ' + str(score), True, red) # Render the game over text
game_over_rect = game_over_surface.get_rect() # Get the rectangle for positioning
game_over_rect.midtop = (size[0] / 2, size[1] / 4) # Position the text at the center top
display.fill(black) # Fill the screen with black color
display.blit(game_over_surface, game_over_rect) # Display the game over text on the screen
show_score(0, red, 'times', 20) # Display the final score
pygame.display.flip() # Update the display
time.sleep(2) # Pause for 2 seconds
pygame.quit() # Quit Pygame
sys.exit() # Exit the program
Main Game Loop
finally, create the main loop for the snake game in Python that handles events, updates the game state, and renders everything on the screen.
while True:
for event in pygame.event.get(): # Process all events
if event.type == pygame.QUIT: # If the event is a quit event
pygame.quit() # Quit Pygame
sys.exit() # Exit the program
elif event.type == pygame.KEYDOWN: # If a key is pressed
if event.key == pygame.K_UP: # If the up arrow key is pressed
change_to = 'UP'
elif event.key == pygame.K_DOWN: # If the down arrow key is pressed
change_to = 'DOWN'
elif event.key == pygame.K_LEFT: # If the left arrow key is pressed
change_to = 'LEFT'
elif event.key == pygame.K_RIGHT: # If the right arrow key is pressed
change_to = 'RIGHT'
# Move the snake
direction = turn_snake(direction, change_to) # Update the direction based on input
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 collision check
if collision_with_bounds(snake_pos) or collision_with_self(snake_body):
game_over()
# Snake eating food
if snake_pos == food_pos:
score += 1
food_spawn = False
else:
snake_body.pop() # Remove the last segment of the snake's body
if not food_spawn:
food_pos = [random.randrange(1, (size[0] // 10)) * 10, random.randrange(1, (size[1] // 10)) * 10] # Generate new food position
food_spawn = True # Set the food spawn flag to true
snake_body.insert(0, list(snake_pos)) # Add the new position of the snake's head to the body
display.fill(black) # Fill the screen with black color
for pos in snake_body: # Draw the snake's body
pygame.draw.rect(display, green, pygame.Rect(pos[0], pos[1], block_size, block_size))
pygame.draw.rect(display, red, pygame.Rect(food_pos[0], food_pos[1], block_size, block_size)) # Draw the food
show_score(1, white, 'consolas', 20) # Display the score
pygame.display.update() # Update the display
pygame.time.Clock().tick(10) # Control the game speed
Output
How to make a snake game in Python? Now you have created a basic Snake game using Python and Pygame. This project covers the essentials of Python & Pygame including user input, updating the game state, and rendering the graphics. Feel free to expand and modify the game by adding new features or improving the graphics to enhance your skills further.
Happy Coding & Learning