In this tutorial, we will learn the step-by-step process of How To Make Snake Game In Python with the help of examples.
What is Snake Game In Python?
One of the most popular arcade games of all time is the Snake game. The main goal of this game is to catch as many food items as possible without hitting the wall or itself.
As you learn Python or Pygame, you can use making a snake game as a challenge. It’s one of the best projects for people who are just starting out in programming, and every beginner should take it on as a challenge. It’s kind of interesting and fun to learn how to make a video game.
Before moving on, let’s have a quick look at all the modules that build snake games in python.
- Installing Libraries
- Create Form
- Create Snake
- Create Moving Snake
- Create A Game Over Function
- Create Function To Add Food
- Create Function To Increase The Length Of Snake
- Display Score
Installing Libraries
Installing libraries is the first thing you’ll need to do if you want to use them to make games. To do this, just type the following command:
import pygame
import time
import random
Create Form
You will need to use the display.set_mode()
function in Pygame to make the screen. Also, you will need to use the init() and quit() methods at the beginning and end of the code to set up and take down everything.
The update() method is used to make the screen reflect any changes that have been made. The flip() method works in a similar way to the update() function.
Also, the update() method only updates the changes that have been made, but if no parameters are given, it updates the whole screen. The flip() method, on the other hand, changes the whole screen again.
import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
pygame.display.update()
pygame.quit()
quit()
But if you run this code, the screen will come up, but it will close right away. To fix that, you should use a game loop with the while loop before I actually quit the game as follows:
import pygame
pygame.init()
dis = pygame.display.set_mode((400, 300))
pygame.display.update()
pygame.display.set_caption('Snake Game by Python For Free')
game_over = False
while not game_over:
for event in pygame.event.get():
print(event) # prints out all the actions that take place on the screen
pygame.quit()
quit()
When you run this code, you’ll see that the screen you just saw doesn’t go away, and it also tells you everything that happens on it. I did that with the help of the function event.get()
. I also used the display.set_caption()
function to give the screen name “Snake Game by Python For Free.”
Now you have a screen where you can play your Snake Game, but when you try to close the screen by clicking the close button, it doesn’t work.
This is because you haven’t specified on your screen that when you click that close button, it should close or exit. To do this, Pygame has a “QUIT” event that should be used as follows:
import pygame
pygame.init()
dis = pygame.display.set_mode((400, 300))
pygame.display.update()
pygame.display.set_caption('Snake Game by Python For Free')
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
pygame.quit()
quit()
Now, after we have set up our form, the next step is to make a snake on the form.
Create Snake
Before I make the snake, I’ll set up a few color variables that will be used to color the snake, its food, the screen, and other things.
RGB, which stands for “Red Green Blue,” is the color scheme used in Pygame. If you set them all to 0, the color will be black, and if you set them all to 255, the color will be white.
So our snake will be a rectangle instead. In Pygame, you can use a function called draw.rect() to draw rectangles in the size and color you want.
import pygame
pygame.init()
dis = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Snake Game by Python For Free')
white = (255, 255, 255)
red = (255, 0, 0)
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
pygame.draw.rect(dis, white, [200, 150, 10, 10])
pygame.display.update()
pygame.quit()
quit()
As you can see, a white rectangle is used to make the snakehead. The next step is to start moving the snake.
Create Moving Snake
To move the snake, you will need to use the KEYDOWN class of Pygame’s key events. Here, the events K_UP, K_DOWN, K_LEFT, and K_RIGHT are used to make the snake move up, down, left, or right. The fill() method also changes the screen from its default black color to white.
import pygame
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
dis = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Snake Game by Python For Free')
game_over = False
x1 = 300
y1 = 300
x1_change = 0
y1_change = 0
clock = pygame.time.Clock()
while not game_over:
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 = -10
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = 10
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -10
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = 10
x1_change = 0
x1 += x1_change
y1 += y1_change
dis.fill(black)
pygame.draw.rect(dis, white, [x1, y1, 10, 10])
pygame.display.update()
clock.tick(30)
pygame.quit()
quit()
Create A Game Over Function
In this snake game, if the player hits the edges of the screen, he loses. To make that clear, I used a “if” statement to set the limits for the x and y coordinates of the snake to be less than or equal to the screen.
Also, note that I have removed the hardcodes and replaced them with variables to make it easier if you want to make changes to the game later.
import pygame
import time
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_width))
pygame.display.set_caption('Snake Game by Python For Free')
game_over = False
x1 = dis_width / 2
y1 = dis_height / 2
snake_block = 10
x1_change = 0
y1_change = 0
clock = pygame.time.Clock()
snake_speed = 30
font_style = pygame.font.SysFont(None, 50)
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 2, dis_height / 2])
while not game_over:
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
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_over = True
x1 += x1_change
y1 += y1_change
dis.fill(black)
pygame.draw.rect(dis, white, [x1, y1, snake_block, snake_block])
pygame.display.update()
clock.tick(snake_speed)
message("You lost", red)
pygame.display.update()
time.sleep(2)
pygame.quit()
quit()
Create Function To Add Food
Here, I’ll put some food for the snake, and when it walks over that food, it will eat it. Also, I will make a small change so that when a player loses, they can choose to either quit the game or try again.
import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Python For Free')
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 30
font_style = pygame.font.SysFont(None, 30)
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 3, dis_height / 3])
def gameLoop(): # creating a function
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
while not game_over:
while game_close == True:
dis.fill(white)
message("You Lost! Press Q>>>Quit or C>>>Play Again", 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:
gameLoop()
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
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(black)
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
pygame.draw.rect(dis, white, [x1, y1, snake_block, snake_block])
pygame.display.update()
if x1 == foodx and y1 == foody:
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
Create Function To Increase The Length Of Snake
The code below will make our snake grow bigger when it eats food. Also, if the snake runs into itself, the game is over and you’ll see a message that says “You Lost!” Press Q>>>Quit or C>>>Play Again”.
The length of the snake is mostly defined by a list, and the following code says that the first size is one block.
import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
dis_width = 600
dis_height = 400
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Python For Free')
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("Courier-new", 35)
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, white, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])
def gameLoop():
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
while not game_over:
while game_close == True:
dis.fill(black)
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:
gameLoop()
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
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(black)
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
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(snake_block, snake_List)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
Display Score
The last thing you need to do is show the player’s score. In order to do this, I made a new function called “Your score.” This function will show the length of the snake minus one, since that is the size of the snake when it starts.
import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
dis_width = 600
dis_height = 400
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Python For Free')
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("courier-new", 35)
def Your_score(score):
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, white, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])
def gameLoop():
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
while not game_over:
while game_close == True:
dis.fill(black)
message("You Lost!!! Press C>>>Play Again or Q>>>Quit", red)
Your_score(Length_of_snake - 1)
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:
gameLoop()
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
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(black)
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
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(snake_block, snake_List)
Your_score(Length_of_snake - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
Conclusion
We have completely discussed the step-by-step process on How To Make Snake Game In Python with the help of examples. I hope this simple game in Python Tutorial will help you a lot.
Thank You!