Build Snake Game using Python

The Coding Hubs
9 Min Read

Hey python junkies we are here with another super exciting topic to make your coding journey entertaining. In this article, we will explore how to create a classic Snake game using Python. Snake game using Python is a simple but addictive game where you get to start and never finish it. The goal is to avoid collisions with the walls and the body of the snake itself. By the end of this article, you will have a fully functional Snake game using Python.

Prerequisites To Build Snake Game using Python

  • Basic understanding of syntax, variables, loops, functions, and conditional statements.
  • Understand the basic concepts of pygame library such as creating a window, handling events, and drawing shapes.
  • Understand the basic game development concepts like game loops, sprites, collision detection, and states.
  • A basic understanding of OOP(Object-Oriented Programming) is recommended.
  • Now let’s build a snake game using Python

To build the Snake game using Python we are going to use pygame module

MODULE used – pygame

Read More: Billing Management System Using Python

Below is the step-by-step guide for a fully developed snake game.

STEP-1: importing the modules:

import pygame
import time
import random

STEP-2: initializing pygame:

pygame.init()

STEP-3: setting the width and height of the screen to the size of a square:

width = 800
height = 600

STEP-4: defining the colors:

white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

STEP-5: setting the size of the block:

block_size = 20

STEP-6: setting the speed of the snake:

speed = 15

STEP-7: setting the font style and size:

font_style = pygame.font.SysFont("bahnschrift", 25)

STEP-8: creating a clock object to control the speed of the game:

clock = pygame.time.Clock()

STEP-9: setting the font style and size:

font_style = pygame.font.SysFont(None, 50)

STEP-10: defining the necessary functions:

  • to draw the snake on the screen:
def our_snake(block_size, snake_list):
    for x in snake_list:
        pygame.draw.rect(screen, black, [x[0], x[1], block_size, block_size])
  • to display messages on the screen:
def message(msg, color):
    mesg = font_style.render(msg, True, color)
    screen.blit(mesg, [width / 6, height / 3])

STEP-11: setting the size of the display:

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

STEP-12: use the loop until the user clicks the close button:

game_over = False
game_close = False

STEP-13: setting the start position of the snake:

x1 = width / 2
y1 = height / 2

STEP-14: setting the change in position for the snake:

x1_change = 0
y1_change = 0

STEP-15: setting the initial length of the snake:

snake_list = []
length_of_snake = 1

STEP-16: setting the position of the food:

foodx = round(random.randrange(0, width - block_size) / block_size) * block_size
foody = round(random.randrange(0, height - block_size) / block_size) * block_size

STEP-17: looping the main game:

while not game_over:
    while game_close == True:
        screen.fill(blue)
        message("You Lost! Press C-Play Again or Q-Quit", red)
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    game_over = True
                    game_close = False
                if event.key == pygame.K_c:
# reset the game
                    x1 = width / 2
 y1 = height / 2
     x1_change = 0
     y1_change = 0
     snake_list = []
     length_of_snake = 1
     foodx = round(random.randrange(0, width -                                                                                                                                     block_size) / block_size) * block_size
     foody = round(random.randrange(0, height - block_size) / block_size) * block_size
      game_close = False
# responding to the events:
	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 = -block_size
                y1_change = 0
            elif event.key == pygame.K_RIGHT:
                x1_change = block_size
                y1_change = 0
            elif event.key == pygame.K_UP:
                y1_change = -block_size
                x1_change = 0
            elif event.key == pygame.K_DOWN:
                y1_change = block_size
                x1_change = 0
# checking if snake hits the boundary:
	  if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
      game_close = True
      x1 += x1_change
      y1 += y1_change
      screen.fill(blue)
# drawing the food:
	      pygame.draw.rect(screen, green, [foodx, foody, block_size, block_size])

    snake_head = []
    snake_head.append(x1)
    snake_head.append(y1)
    snake_list.append(snake_head)
    if len(snake_list) > length_of_snake:
        del snake_list[0]

    for x in snake_list[:-1]:
        if x == snake_head:
            game_close = True
    our_snake(block_size, snake_list)
    pygame.display.update()
# checking if the snake hits the food:
	  if x1 == foodx and y1 == foody:
        foodx = round(random.randrange(0, width - block_size) / block_size) * block_size
      foody = round(random.randrange(0, height - block_size) / block_size) * block_size
        length_of_snake += 1
# setting the speed of the game:
	  clock.tick(speed)

STEP-18: Closing the pygame window:

pygame.quit()
quit()

Snake Game Using Python Source Code

import pygame
import time
import random

pygame.init()

width = 800
height = 600

white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

block_size = 20
speed = 15

font_style = pygame.font.SysFont("bahnschrift", 25)

clock = pygame.time.Clock()

font_style = pygame.font.SysFont(None, 50)


def our_snake(block_size, snake_list):
    for x in snake_list:
        pygame.draw.rect(screen, black, [x[0], x[1], block_size, block_size])


def message(msg, color):
    mesg = font_style.render(msg, True, color)
    screen.blit(mesg, [width / 6, height / 3])

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

game_over = False
game_close = False

x1 = width / 2
y1 = height / 2

x1_change = 0
y1_change = 0

snake_list = []
length_of_snake = 1

foodx = round(random.randrange(0, width - block_size) / block_size) * block_size
foody = round(random.randrange(0, height - block_size) / block_size) * block_size

# Main game loop
while not game_over:

    while game_close == True:
        screen.fill(blue)
        message("You Lost! Press C-Play Again or Q-Quit", red)
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    game_over = True
                    game_close = False
                if event.key == pygame.K_c:
                    # Reset the game
                    x1 = width / 2
                    y1 = height / 2
                    x1_change = 0
                    y1_change = 0
                    snake_list = []
                    length_of_snake = 1
                    foodx = round(random.randrange(0, width - block_size) / block_size) * block_size
                    foody = round(random.randrange(0, height - block_size) / block_size) * block_size
                    game_close = False
    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 = -block_size
                y1_change = 0
            elif event.key == pygame.K_RIGHT:
                x1_change = block_size
                y1_change = 0
            elif event.key == pygame.K_UP:
                y1_change = -block_size
                x1_change = 0
            elif event.key == pygame.K_DOWN:
                y1_change = 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(blue)
    pygame.draw.rect(screen, green, [foodx, foody, block_size, block_size])
    snake_head = []
    snake_head.append(x1)
    snake_head.append(y1)
    snake_list.append(snake_head)
    if len(snake_list) > length_of_snake:
        del snake_list[0]
    for x in snake_list[:-1]:
        if x == snake_head:
            game_close = True
    our_snake(block_size, snake_list)
    pygame.display.update()
    if x1 == foodx and y1 == foody:
        foodx = round(random.randrange(0, width - block_size) / block_size) * block_size
        foody = round(random.randrange(0, height - block_size) / block_size) * block_size
        length_of_snake += 1
    clock.tick(speed)
pygame.quit()
quit()
Read More: Random Password Generator Using Python

Output of Snake Game Using Python

Snake Game In Python
Read More: YouTube Video Downloader Using Python

Conclusion

In this article, I shared how to Build a Snake Game Using Python with Source Code.  I hope you enjoyed reading this tutorial and found the information provided on how to Build a Snake Game Using Python. Embrace yourself as, unlike others, you are trying something new.

Share This Article
Follow:
I'm a Programmer and Content Creator, crafting code and blogs since 2015. Passionate about simplifying complex ideas, I thrive on sharing knowledge through programming projects and engaging articles.
1 Comment
  • That is very interesting, You’re a very professional blogger. I’ve joined your rss feed and stay up for seeking extra of your magnificent post. Additionally, I have shared your web site in my social networks!

Leave a Reply

Your email address will not be published. Required fields are marked *