Table of contents
1.
Introduction
2.
Building Snake Game using PyGame
2.1.
Completed steps
2.2.
Remaining Steps
3.
Continue Code
3.1.
Stage 6: Now, we will make our primary capacity that will do the accompanying things:
4.
Final Stage: Implementation of game
5.
FAQs
6.
Key Takeaways
Last Updated: Aug 13, 2025
Easy

Building Snake Game using PyGame: Part 2

Author Adya Tiwari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Snake Game in Python utilizes Pygame, a free and open-source Python library used to make games. The snake was an unquestionably famous game, generally recollected from the 1990s time cells. It was the main game on their telephone for some individuals around then. It is also an excellent game from which to gain the fundamentals of game making.

Building Snake Game using PyGame

We have completed the installation of PyGame and imported the necessary libraries in the first part of the article. We had also started coding and met a few steps towards the complete success of the game. Let's recap and remember the actions that we had assembled in the previous article.


Completed steps

Step 1: Import necessary libraries

Stage 2: After bringing in libraries, we want to instate Pygame utilizing pygame.init() technique which helps to initialize all imported pygame modules.

Stage 3: Initialize snake position and its size.

Stage 4: Create a capacity to show the score of the player.

Step 5: Now, create a game over function that will represent the score after the snake is hit by a wall or itself. 

Remaining Steps

Shoot, Bunny, Shoot!

Take Up Arms! Badgers!

Collisions with Badgers and Arrows 

Add a HUD with Health Meter and Clock

Win or Lose

Gratuitous Music and Sound Effects

Continue Code

Stage 6: Now, we will make our primary capacity that will do the accompanying things:

 

  • We will be approving the keys that will be answerable for the development of the snake; then we will make a great condition that the snake ought not to be permitted to move the other way momentarily.
  • From that point onward, assuming snake and natural product impact, we will be augmenting the score by ten, and, new natural products will be traversed.
  • From that point onward, we are making sure that is the snake is hit with a divider or not. Assuming a snake reaches a stopping point, we will bring game overwork.
  • If the snake hits itself, the game overcapacity will be called.
  • Furthermore, eventually, we will show the scores utilizing the show_score work made before.

 

# Main Function
while True:
   
    # handling key events
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                change_to = 'UP'
            if event.key == pygame.K_DOWN:
                change_to = 'DOWN'
            if event.key == pygame.K_LEFT:
                change_to = 'LEFT'
            if event.key == pygame.K_RIGHT:
                change_to = 'RIGHT'
 
    # If two keys pressed simultaneously
    # we don't want snake to move into two directions
    # simultaneously
    if change_to == 'UP' and direction != 'DOWN':
        direction = 'UP'
    if change_to == 'DOWN' and direction != 'UP':
        direction = 'DOWN'
    if change_to == 'LEFT' and direction != 'RIGHT':
        direction = 'LEFT'
    if change_to == 'RIGHT' and direction != 'LEFT':
        direction = 'RIGHT'
 
    # Moving the snake
    if direction == 'UP':
        snake_position[1] -= 10
    if direction == 'DOWN':
        snake_position[1] += 10
    if direction == 'LEFT':
        snake_position[0] -= 10
    if direction == 'RIGHT':
        snake_position[0] += 10
 
    # Snake body growing mechanism
    # if fruits and snakes collide then scores will be
    # incremented by 10
    snake_body.insert(0, list(snake_position))
    if snake_position[0] == fruit_position[0] and snake_position[1] == fruit_position[1]:
        score += 10
        fruit_spawn = False
    else:
        snake_body.pop()
         
    if not fruit_spawn:
        fruit_position = [random.randrange(1, (window_x//10)) * 10,
                          random.randrange(1, (window_y//10)) * 10]
         
    fruit_spawn = True
    game_window.fill(black)
     
    for pos in snake_body:
        pygame.draw.rect(game_window, green, pygame.Rect(
          pos[0], pos[1], 10, 10))
         
    pygame.draw.rect(game_window, white, pygame.Rect(
      fruit_position[0], fruit_position[1], 10, 10))
 
    # Game Over conditions
    if snake_position[0] < 0 or snake_position[0] > window_x-10:
        game_over()
    if snake_position[1] < 0 or snake_position[1] > window_y-10:
        game_over()
     
    # Touching the snake body
    for block in snake_body[1:]:
        if snake_position[0] == block[0] and snake_position[1] == block[1]:
            game_over()
     
    # displaying score countinuously
    show_score(1, white, 'times new roman', 20)
     
    # Refresh game screen
    pygame.display.update()
 
    # Frame Per Second /Refresh Rate
    fps.tick(snake_speed)
You can also try this code with Online Python Compiler
Run Code

Final Stage: Implementation of game

Compile all the given codes into one to get the game's final results. 
The game can be visualized in a black background with the snake and food that will appear at random places given by x and y coordinates. The score can be seen at the top left corner of the screen. Each block that will be eaten by the snake will make it grow one unit (increment 10)  bigger increasing the score and making the game more challenging and fun. If fruits and snake collide the score will increase by 10 as will the size of the snake. The score will be displayed in Time new roman font size 20. If two keys are pressed simultaneously we don't want directions to get confused so we have given unique and particular functions for each direction key.

The fruit is created by creating a rectangular object that is generated at random places once. Blit has been used to draw text on the screen. 
This is what the game will look like after full execution.


FAQs

1. What is the blit function used for?
Blit is used to draw text on screen while coding. 

2. What are the benefits of creating the snake game?
This game is an excellent opportunity to learn about spatial awareness and plan ahead to your next move. It is also a good entertainment mixed with brain exercise and now can easily be creating with the help of PyGame. 

3. What are some updates that can be made in the Snake game further?
This game can have several updates as its only a basic code. Updates can be done in the body of the snake, fruits, background etc. to make it more interactive.

4. Why should one start by creating the Snake game first in Pygame?
The Snake game code here has been designed specially for beginners to learn and as it is a basic game with short code and no complication, it will be great for beginners.

Key Takeaways

PyGame is a library for the Python programming language that gives an item situated application programming connection point for making games and other media applications. The game includes characters such as Change in the score, Color coordination, background color, the position of objects, i.e., snake and food, etc. The code for this game is simple and short specially suited for beginners and can help in quick learning.

Check out this problem - Optimal Strategy For A Game

Hey Ninjas! Don’t stop here; check out Coding Ninjas for ML, more unique courses, and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Gaming and Python problems. 

Happy Learning!

 

Live masterclass