Introduction
This project will guide you through the process of creating a snake game using Python and the Pygame library. The game will have a game window, a snake, a power-up, and a score. The snake will move around the game window and eat the power-up. When the snake eats the power-up, the length of the snake will be increased by one. The score will be displayed on the screen.
👀 Preview

🎯 Tasks
In this project, you will learn:
- How to create a game window using Pygame
- How to handle user input to control the snake's movement
- How to create and update the snake's position
- How to draw the snake and the power-up on the screen
- How to detect collisions between the snake and the power-up
- How to keep track of the score
- How to display the score on the screen
🏆 Achievements
After completing this project, you will be able to:
- Use Pygame to create a graphical game window
- Handle user input to control the game
- Create and update game objects
- Detect collisions in a game
- Display and update the game score
Create the project files
Create a new file named snake_game.py and open it in a code editor.
cd ~/project
touch snake_game.py
sudo pip install pygame
Import necessary modules
In the snake_game.py file, import the pygame and random modules:
import pygame
import random
Initialize Pygame
After importing the modules, initialize Pygame:
pygame.init()
Set up the game window
Define the width, height, and frames per second (FPS) of the game window:
WIDTH = 800
HEIGHT = 600
FPS = 10
Define colors
Define the colors used in the game:
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
BACKGROUND_COLOR = (50, 50, 50)
Set up the game window
Set up the game window with the defined width and height:
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
clock = pygame.time.Clock()
In above code, pygame.display.set_mode() is used to initialize the display with the specified width and height. pygame.display.set_caption() is used to set the title of the game window. pygame.time.Clock() is used to track time in the game.
Set up the snake
Define the block size and speed of the snake:
snake_block_size = 20
snake_speed = 5
We set the block size to 20 and the speed to 5. This means that the snake will move 5 pixels at a time.
Set up the game variables
Define the font styles and font sizes for displaying the score:
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
Set up the power-up
Define the block size of the power-up:
powerup_block_size = 20
Define functions
Define the following functions:
draw_snake(snake_block_size, snake_list)
This function draws the snake on the screen:
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(
screen, GREEN, [x[0], x[1], snake_block_size, snake_block_size]
)
In the above code, pygame.draw.rect() is used to draw a rectangle on the screen. The first parameter is the screen, the second parameter is the color, and the third parameter is the position and size of the rectangle.
draw_powerup(powerup_x, powerup_y)
This function draws the power-up on the screen:
def draw_powerup(powerup_x, powerup_y):
pygame.draw.rect(
screen, RED, [powerup_x, powerup_y, powerup_block_size, powerup_block_size]
)
In the above code, pygame.draw.rect() is used to draw a rectangle on the screen. The first parameter is the screen, the second parameter is the color, and the third parameter is the position and size of the rectangle.
display_score(score)
This function displays the score on the screen:
def display_score(score):
value = score_font.render("Score: " + str(score), True, WHITE)
screen.blit(value, [10, 10])
In the above code, score_font.render() is used to render the score on the screen. The first parameter is the text to be displayed, the second parameter is the anti-aliasing, and the third parameter is the color of the text. screen.blit() is used to draw the text on the screen. The first parameter is the text to be displayed, and the second parameter is the position of the text.
game_loop()
This function contains the main game loop:
def game_loop():
## Game loop code goes here
Complete the game loop code
Complete the game_loop() function by adding the game logic inside the while loop.
def game_loop():
game_over = False
game_close = False
## Set up the snake's starting position
x1 = WIDTH / 2
y1 = HEIGHT / 2
x1_change = 0
y1_change = 0
## Set up the snake's body
snake_list = []
snake_length = 1
## Set up the power-up
powerup_x = round(random.randrange(0, WIDTH - powerup_block_size) / 20) * 20
powerup_y = round(random.randrange(0, HEIGHT - powerup_block_size) / 20) * 20
## Set up the game loop
while not game_over:
while game_close:
screen.fill(BACKGROUND_COLOR)
message = font_style.render("Press SPACE to play again", True, YELLOW)
screen.blit(message, [WIDTH / 2 - 200, HEIGHT / 2 - 50])
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
game_close = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
game_loop()
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:
x1_change = -snake_block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block_size
x1_change = 0
if x1 >= WIDTH or x1 < 0 or y1 >= HEIGHT or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
screen.fill(BACKGROUND_COLOR)
pygame.draw.rect(
screen, BLUE, [powerup_x, powerup_y, powerup_block_size, powerup_block_size]
)
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
draw_snake(snake_block_size, snake_list)
display_score(snake_length - 1)
pygame.display.flip()
if x1 == powerup_x and y1 == powerup_y:
powerup_x = round(random.randrange(0, WIDTH - powerup_block_size) / 20) * 20
powerup_y = (
round(random.randrange(0, HEIGHT - powerup_block_size) / 20) * 20
)
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
In the above code, pygame.QUIT is used to quit the game. pygame.KEYDOWN is used to check if a key is pressed. pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, and pygame.K_DOWN are used to check if the left, right, up, and down arrow keys are pressed, respectively. pygame.draw.rect() is used to draw a rectangle on the screen. The first parameter is the screen, the second parameter is the color, and the third parameter is the position and size of the rectangle. pygame.display.flip() is used to update the screen. pygame.time.Clock() is used to track time in the game. pygame.time.Clock.tick() is used to set the FPS of the game.
Run the game
Add the following at the end of the file to run the game:
game_loop()
pygame.quit()
Finally, switch to Desktop and run the project using the following command:
python snake_game.py

Summary
Congratulations! You have successfully created a snake game using Python and the Pygame library. In this project, you learned how to set up the game window, define colors, draw the snake and power-up, display the score, and implement the game logic. You can now run the game and enjoy playing it.



