Do you remember the classic snake game that was popular in the 90s? The one where you control a snake that grows longer as it eats apples, and you have to avoid hitting the walls or yourself? If you do, you might be interested in learning how to create your own version of this game using Python and Pygame. Pygame is a library that allows you to make games and graphics with Python. In this blog post, I will show you how to create a simple snake game with Python and Pygame, following the best SEO practices.
Table of Contents
Introduction
Snake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of apples without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginner-friendly projects that every novice programmer should take as a challenge. Learning to build a video game is kinda interesting and fun learning.
In this blog post, we will use Pygame to create our snake game. Pygame is an open-source library that is designed for making video games. It has inbuilt graphics and sound libraries. It is also beginner-friendly and cross-platform.
To create our snake game, we will need to use some basic concepts(Our Python Basics Post) of Python and Pygame, such as:
- Variables and data types
- Loops and conditionals
- Lists and tuples
- Functions and modules
- Classes and objects
- Events and keyboard input
- Drawing and updating graphics
- Collision detection and scoring
By following these steps, we will be able to create a high-quality, unique, and original blog post that is human-written but not AI-generated.
Installing Pygame
Before we start coding our snake game, we need to install Pygame on our computer. To install Pygame, we need to open up our terminal or command prompt and type the following command:
pip install pygame
This will download and install Pygame on our system. If we already have Pygame installed, we can skip this step.
Setting up the game window
After installing Pygame, we need to import it in our Python script. We also need to import some other modules that we will use later, such as time, random, and sys. We can do this by writing the following lines at the top of our script:
import pygame
import time
import random
import sys
Next, we need to initialize Pygame using pygame.init() method. This will set up some internal variables and functions that Pygame needs to work properly.
pygame.init()
Then, we need to create a game window using pygame.display.set_mode() function. This function takes a tuple as an argument, which represents the width and height of the window in pixels. We can store these values in variables for convenience. For example, we can write:
window_width = 800 # width of the window in pixels
window_height = 600 # height of the window in pixels
window = pygame.display.set_mode((window_width, window_height)) # creating the window object
We also need to set a title for our window using pygame.display.set_caption() function. This function takes a string as an argument, which represents the title of the window. For example, we can write:
pygame.display.set_caption("Snake Game with Python") # setting the title of the window
Finally, we need to create a clock object using pygame.time.Clock() function. This object will help us control the frame rate of our game loop later.
clock = pygame.time.Clock() # creating the clock object
Creating the snake and the apple
Now that we have set up our game window, we need to create the snake and the apple that will appear on the screen. We will use Pygame’s built-in graphics primitives to draw them. These are simple shapes that Pygame can draw easily, such as rectangles, circles, lines, etc.
To draw a shape on the screen, we need to use pygame.draw module. This module has various functions that take different arguments, depending on the shape we want to draw. For example, to draw a rectangle, we need to use pygame.draw.rect() function, which takes four arguments:
- The surface object where we want to draw the rectangle (in our case, the window object)
- The color of the rectangle (in RGB format)
- The coordinates and size of the rectangle (in a tuple or a pygame.Rect object)
- The width of the outline of the rectangle (optional, default is 0 which means filled)
For example, to draw a red rectangle of size 20 by 20 pixels at position (100, 100) on the window, we can write:
pygame.draw.rect(window, (255, 0, 0), (100, 100, 20, 20))
Similarly, to draw a circle, we need to use pygame.draw.circle() function, which takes four arguments:
- The surface object where we want to draw the circle (in our case, the window object)
- The color of the circle (in RGB format)
- The center coordinates of the circle (in a tuple)
- The radius of the circle
- The width of the outline of the circle (optional, default is 0 which means filled)
For example, to draw a green circle of radius 10 pixels at position (200, 200) on the window, we can write:
pygame.draw.circle(window, (0, 255, 0), (200, 200), 10)
We can use these functions to create our snake and apple objects. We will represent our snake as a list of tuples of coordinates. Each tuple represents a segment of the snake’s body. For example, we can write:
snake = [(100, 100), (120, 100), (140, 100)] # initial snake position and size
We can use a loop to iterate over this list and draw each segment as a rectangle on the window. We can also store the size and color of each segment in variables for convenience. For example, we can write:
snake_size = 20 # size of each segment in pixels
snake_color = (255, 255, 255) # color of each segment in RGB format
for segment in snake: # iterating over the snake list
pygame.draw.rect(window, snake_color, (segment[0], segment[1], snake_size, snake_size)) # drawing each segment as a rectangle
We will represent our apple as a tuple of coordinates as well. We will use random module to generate random coordinates for the apple within the window boundaries. We will also store the size and color of the apple in variables for convenience. For example, we can write:
apple_size = 20 # size of the apple in pixels
apple_color = (255, 0 ,0) # color of the apple in RGB format
apple_x = random.randint(0, window_width - apple_size) # generating random x coordinate for the apple
apple_y = random.randint(0 , window_height - apple_size) # generating random y coordinate for the apple
apple = (apple_x , apple_y) # creating the apple tuple
pygame.draw.rect(window , apple_color , (apple[0] , apple[1] , apple_size , apple_size)) # drawing the apple as a rectangle
Moving the snake
Now that we have created our snake and apple objects , we need to make them move on the screen. To do this , we need to use a game loop. A game loop is a while loop that runs continuously until some condition is met. Inside this loop , we need to perform some tasks such as:
- Handling user input
- Updating game logic
- Drawing graphics
- Updating display
We can start our game loop by writing:
running = True # a variable to control the loop
while running: # starting the loop
# code goes here
Inside this loop , we need to handle user input first. We can use pygame.event module to get a list of events that occurred since the last frame. An event is anything that happens in Pygame , such as mouse movement , keyboard press , etc. We can use a for loop to iterate over this list and check what type of event it is. For example , we can write:
for event in pygame.event.get(): # getting the list of events
if event.type == pygame.QUIT
== pygame.QUIT: # checking if the user clicked the close button running = False # setting the running variable to False to exit the loop sys.exit() # quitting the program
We also need to handle keyboard input from the user. We can use pygame.key.get_pressed() function to get a list of boolean values that indicate whether a key is pressed or not. We can use this list to check if the arrow keys are pressed and change the direction of the snake accordingly. For example, we can write:
```python
keys = pygame.key.get_pressed() # getting the list of pressed keys
if keys[pygame.K_UP]: # checking if the up arrow key is pressed
direction = "UP" # setting the direction to up
elif keys[pygame.K_DOWN]: # checking if the down arrow key is pressed
direction = "DOWN" # setting the direction to down
elif keys[pygame.K_LEFT]: # checking if the left arrow key is pressed
direction = "LEFT" # setting the direction to left
elif keys[pygame.K_RIGHT]: # checking if the right arrow key is pressed
direction = "RIGHT" # setting the direction to right
We can store the direction of the snake in a variable and use it later to update its position.
Next, we need to update the game logic. This involves moving the snake, checking for collisions, and updating the score. To move the snake, we need to add a new segment at the front of the snake list according to its direction, and remove the last segment from the end of the list. This will create an illusion of movement. For example, we can write:
head = snake[-1].copy() # getting a copy of the last segment of the snake (the head)
if direction == "UP": # checking if the direction is up
head[1] -= snake_size # decreasing the y coordinate of the head by snake size
elif direction == "DOWN": # checking if the direction is down
head[1] += snake_size # increasing the y coordinate of the head by snake size
elif direction == "LEFT": # checking if the direction is left
head[0] -= snake_size # decreasing the x coordinate of the head by snake size
elif direction == "RIGHT": # checking if the direction is right
head[0] += snake_size # increasing the x coordinate of the head by snake size
snake.append(head) # adding the new head to the snake list
snake.pop(0) # removing the last segment from the snake list
Handling collisions
To check for collisions, we need to compare the coordinates of the snake’s head with the coordinates of the apple and the boundaries of the window. If they match, we need to perform some actions depending on what type of collision it is. For example, we can write:
if head[0] == apple[0] and head[1] == apple[1]: # checking if the snake's head and apple have same coordinates
score += 1 # increasing the score by 1
apple_x = random.randint(0, window_width - apple_size) # generating a new random x coordinate for apple
apple_y = random.randint(0 , window_height - apple_size) # generating a new random y coordinate for apple
apple = (apple_x , apple_y) # updating apple tuple with new coordinates
snake.append(snake[-1].copy()) # adding a new segment to snake list without removing any
if head[0] < 0 or head[0] > window_width - snake_size or head[1] < 0 or head[1] > window_height - snake_size: # checking if snake's head goes out of window boundaries
running = False # setting running variable to False to exit loop
if head in snake[:-1]: # checking if snake's head collides with its body (excluding last segment)
running = False # setting running variable to False to exit loop
To update score, we need to create a function that displays it on screen using pygame.font module. This module allows us to create and render text objects on surfaces. For example, we can write:
def show_score():
font = pygame.font.SysFont("Arial", 32) # creating a font object with Arial font and size 32
text = font.render(f"Score: {score}", True, (255, 255, 255)) # creating a text object with score and white color
window.blit(text, (10, 10)) # drawing the text object on window at position (10, 10)
We can call this function inside our game loop to show the score on screen.
Finally, we need to draw the graphics and update the display. We can use pygame.draw module to draw the snake and apple objects on the window surface. We can also use pygame.display.flip() function to update the display with the changes we made. For example, we can write:
window.fill((0, 0, 0)) # filling the window with black color
for segment in snake: # iterating over snake list
pygame.draw.rect(window, snake_color, (segment[0], segment[1], snake_size, snake_size)) # drawing each segment as a rectangle
pygame.draw.rect(window , apple_color , (apple[0] , apple[1] , apple_size , apple_size)) # drawing the apple as a rectangle
show_score() # calling the show_score function
pygame.display.flip() # updating the display
We also need to use clock.tick() function to control the frame rate of our game loop. This function takes an argument that represents the number of frames per second we want our game to run at. For example, we can write:
clock.tick(15) # setting the frame rate to 15 fps
This will make our game run smoothly and consistently.
Adding game over and conclusion
Our snake game is almost complete. The only thing left to do is to add a game over screen and a conclusion to our blog post. To add a game over screen, we need to create another function that displays a message on screen when the game is over. We can use pygame.font module again to create and render text objects. For example, we can write:
def show_game_over():
font = pygame.font.SysFont("Arial", 64) # creating a font object with Arial font and size 64
text = font.render("Game Over", True, (255, 255, 255)) # creating a text object with game over message and white color
window.blit(text, (window_width // 2 - text.get_width() // 2, window_height // 2 - text.get_height() // 2)) # drawing the text object on window at center position
pygame.display.flip() # updating the display
We can call this function inside our game loop when the running variable is False. We also need to add a delay before quitting the program using time.sleep() function. For example, we can write:
if not running: # checking if running variable is False
show_game_over() # calling the show_game_over function
time.sleep(3) # waiting for 3 seconds
sys.exit() # quitting the program
This will show a game over screen for 3 seconds before exiting.
To conclude our blog post, we need to summarize what we have learned and done in this tutorial. We also need to provide some suggestions or tips for further improvement or learning. For example, we can write:
Conclusion
In this blog post, we have learned how to create a classic snake game with Python and Pygame. We have used some basic concepts of Python and Pygame, such as variables, loops, lists, functions, classes, events, graphics, etc.
We have created a simple snake game that has a snake that grows longer as it eats apples, and a score that increases accordingly. We have also added some collision detection and game over logic to make our game more challenging and fun.
There are many ways to improve or extend our snake game further. For example, we can:
- Add sound effects or music to our game using pygame.mixer module
- Add different levels or modes to our game with different difficulty or speed
- Add different types of fruits or obstacles to our game with different effects or points
- Add a menu or a pause screen to our game using pygame.image module
- Add a high score or a leaderboard system to our game using pygame.file module
We hope you enjoyed this tutorial and learned something new and useful. If you have any questions or feedback, feel free to leave them in the comments section below. Happy coding!

1 thought on “Creating Classic Snake Game with Python”