Step-by-step Pygame Tutorial: Build Save the Spider Game from Scratch

Use Pygame to create an interactive game

Most of us have played a computer game, and some have wondered how to create our own. Luckily, there are packages for several languages that allow us to do that. Python has a library called Pygame, a set of Python modules designed for building video games. Pygame provides functionalities for creating graphical applications, handling input from devices like a keyboard and a mouse, and managing sound and music.

To illustrate how PyGame works, we will walk you step-by-step through the creation of a game called Save the Spider.

To start, we will show you how to set up the development environment, then explore the game’s mechanics, and then show you how to code everything out.

Setting up the environment

To set up the environment, you’ll need Python installed on your computer. If you don’t have it, head over to the official Python website and download the latest version.

Install Pygame

With Python installed, use its package installer called pip to install pygame. To do this, open the command prompt and run the following command:

pip install pygame

Now, you have Pygame installed on your system. Next, you will download the required assets to build the game.

Download Assets

While building the game, we’ll use some assets like images and GIFs to make the game engaging and interactive.

Visit this link to download the resources required to build the Save the Spider game using Pygame.

** Note**: You can use your own images/GIFs too.

Overview of the Save the Spider Game

Now, let’s understand how the Save the Spider game works. Save the Spider is a simple game where the player controls a spider that tries to jump between sets of snakes without hitting them. The spider is continuously pulled down by gravity, and the player must press the spacebar key to make the spider jump to avoid the snakes.

That’s it, we are ready to build the game!

Build Save the Spider with Pygame from Scratch

Let’s get into building the game using Pygame. Here are the steps that we are going to follow for the development: steps to develop save the spider game using pygame

Initialize Pygame

First, you’ll need to set up Pygame. This involves importing necessary modules and initializing Pygame itself. We’ll import the following libraries:

  • pygame for game functionalities
  • sys for system operations
  • random for generating random pipe positions:

We will initialize everything after importing it.

import pygame, sys, random
# Initialize Pygame
pygame.init()
screen = pygame.display.set_mode((576, 1024))
clock = pygame.time.Clock()
game_font = pygame.font.Font('04B_19.ttf', 40)
  • In the above code, pygame.init() initializes all the Pygame modules.
  • The pygame.display.set_mode((Width, Height)) creates the game window with a resolution of 576x1024 pixels.
  • pygame.time.Clock() helps us manage the game’s frame rate
  • The pygame.font.Font('04B_19.ttf', 40) loads a custom font for displaying text on the screen.

Drawing and Animating the Floor

The following function, draw_floor(), is responsible for rendering the floor on the game screen.

def draw_floor():
screen.blit(floor_surface, (floor_x_pos, 900))
screen.blit(floor_surface, (floor_x_pos + 576, 900))

In the draw_floor() function, the screen.blit() function draws the floor_surface image onto the screen at the initial position of the floor. The second call to screen.blit() places another instance of the floor image immediately to the right of the first one to create the illusion of a continuous floor.

Creating and managing Pipes

To manage pipes, we’ll create four functions:

  • create_snake():

First, the create_snake() function selects a random value from the snake_height list and stores it in random_snake_pos, then the top and bottom snakes are created using the random value stored in random_snake_pos.

def create_snake():
random_snake_pos = random.choice(snake_height)
bottom_snake = snake_surface.get_rect(midtop=(700, random_snake_pos))
top_snake = snake_surface.get_rect(midbottom=(700, random_snake_pos - 300))
return bottom_snake, top_snake
  • move_snakes():

The move_snakes() shifts all snakes to the left by 5 pixels, simulating movement and filters out any snakes that have moved off the screen to improve performance and keep the game clean.

def move_snakes(snakes):
for snake in snakes:
snake.centerx -= 5
visible_snakes = [snake for snake in snakes if snake.right > -50]
return visible_snakes
  • draw_snakes():

In the draw_snakes() function goes through each snake in the snakes list, determines if each snake is a bottom or top snake based on its bottom attribute. It then draws the bottom snakes normally and for top snakes it flips the images vertically.

def draw_snakes(snakes):
for snake in snakes:
if snake.bottom >= 1024:
screen.blit(snake_surface, snake)
else:
flip_snake = pygame.transform.flip(snake_surface, False, True)
screen.blit(flip_snake, snake)
  • check_collision():

The check_collision() function checks for two types of collisions:

  • with the snakes
  • with the screen boundaries.

If any collision is detected, it returns False or else True.

def check_collision(snakes):
for snake in snakes:
if spider_rect.colliderect(snake):
return False
if spider_rect.top <= -100 or spider_rect.bottom >= 900:
return False
return True

Creating Game Variables and Assets

We’ll define some important game variables and load the required images into our code.

First, let’s declare these variables:

  • gravity: Defines the gravitational pull that affects the spider.
  • spider_movement: Keeps track of the current vertical movement of the spider.
  • game_active: This boolean variable indicates whether the game is currently active or not.
  • score: Keeps track of the player’s current score.
  • high_score: Stores the highest score the player has achieved across all game sessions.
  • can_score: It is used to control when the player can earn points.
# Game Variables
gravity = 0.1 # Reduced gravity
bird_movement = 0
game_active = True
score = 0
high_score = 0
can_score = True

Now we are done with pre-defined game variables. Let’s make the game interactive with graphic elements.

We’ll use assets to represent the spider, snakes, floor, etc. Assets are images/GIFs to make the game characters visible on screen. We use pygame.image.load() function to load the assets in our code.

First, we’ll load and scale the background(background-day.png) and floor(base.png) images that initialize the floor’s position:

bg_surface = pygame.image.load('assets/background-day.png').convert()
bg_surface = pygame.transform.scale2x(bg_surface)
floor_surface = pygame.image.load('assets/base.png').convert()
floor_surface = pygame.transform.scale2x(floor_surface)
floor_x_pos = 0

Now, load, scale, and position the spider image at coordinates (100, 512) on the screen.

spider_surface = pygame.transform.scale2x(pygame.image.load('assets/spider.png').convert_alpha())
spider_rect = spider_surface.get_rect(center=(100, 512))

Then load the snake image. We’ll initialize an empty list snake_list to track snake obstacles, set a timer to spawn new snakes every 1.2 seconds, and define possible heights for snake spawning which will be either 400, 600, or 800.

snake_surface = pygame.image.load('assets/snake_pipe.png')
snake_surface = pygame.transform.scale2x(snake_surface)
snake_list = []
SPAWNSNAKE = pygame.USEREVENT
pygame.time.set_timer(SPAWNSNAKE, 1200)
snake_height = [400, 600, 800]

At last, we’ll load the game over screen.

game_over_surface = pygame.transform.scale2x(pygame.image.load('assets/message.png').convert_alpha())
game_over_rect = game_over_surface.get_rect(center=(288, 512))

Scoring System

The scoring system in Save the Spider is designed to track the player’s progress. It keeps track of the current score and the highest score.

  • score_display():

The score_display() function displays the score in a specific position based on the game_state:

def score_display(game_state):
if game_state == 'main_game':
score_surface = game_font.render(str(int(score)), True, (255, 255, 255))
score_rect = score_surface.get_rect(center=(288, 100))
screen.blit(score_surface, score_rect)
if game_state == 'game_over':
score_surface = game_font.render(f'Score: {int(score)}', True, (255, 255, 255))
score_rect = score_surface.get_rect(center=(288, 100))
screen.blit(score_surface, score_rect)
  • update_score():

This function ensures that the high score is updated if the current score exceeds it.

def update_score(score, high_score):
if score > high_score:
high_score = score
return high_score
  • snake_score_check():

This function increments the score when the spider successfully passes through a set of snakes.

def snake_score_check():
global score, can_score
if snake_list:
for snake in snake_list:
if 95 < snake.centerx < 105 and can_score:
score += 1
can_score = False
if snake.centerx < 0:
can_score = True

Main While loop

The main game loop continuously handles events, updates game elements, and redraws the screen to ensure smooth and engaging gameplay.

First, let’s add a code to manage Pygame events, such as quitting the game and detecting key presses. It’ll handle the spacebar press differently based on the game state and triggers the creation of new snakes when a custom SPAWNSNAKE event occurs:

for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and game_active:
spider_movement = 0
spider_movement -= 6
if event.key == pygame.K_SPACE and not game_active:
game_active = True
snake_list.clear()
spider_rect.center = (100, 512)
spider_movement = 0
score = 0
if event.type == SPAWNSNAKE:
snake_list.extend(create_snake())

The following code will manage the game’s main loop. During active gameplay, it applies gravity to the spider’s movement, updates snake positions, checks for collisions, and handles score updates. When the game is inactive, it displays the game on the screen:

screen.blit(bg_surface, (0, 0))
if game_active:
spider_movement += gravity
spider_rect.centery += spider_movement
screen.blit(spider_surface, spider_rect)
game_active = check_collision(snake_list)
snake_list = move_snakes(snake_list)
draw_snakes(snake_list)
snake_score_check()
score_display('main_game')
else:
screen.blit(game_over_surface, game_over_rect)
high_score = update_score(score, high_score)
score_display('game_over')

Now, we’ll add code to move the floor surface to create an illusion of continuous horizontal movement. We’ll decrement the floor_x_pos variable by 1 in each frame and if the floor’s position exceeds the width of the screen (576 pixels), it resets floor_x_pos to 0:

floor_x_pos -= 1
draw_floor()
if floor_x_pos <= -576:
floor_x_pos = 0

In the end, we’ll make sure the frame rate does not exceed 120 frames per second:

pygame.display.update()
clock.tick(120)

If you follow all the steps, run the file and the game should look like this: save the spider code output

Conclusion

Well done! You’ve successfully created the Save the Spider game using Pygame from scratch.

We learned:

  • Pygame is a Python library designed for building video games.
  • You can install it using pip install pygame command.
  • Save the Spider is a game where you control the spider and try not to hit the set of snakes.

In this game, we created different functions to structure the game and used those functions in an infinite while loop for a smooth experience.

Author

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team