Python snake game code with Pygame
In this article, you will learn how to develop a snake game program using Python Pygame. We hope you have played the snake game. This is one of the loveliest games for kids. Have you thought? How to develop this game? Here, we have mentioned the step-by-step process for developing the snake game.
Install Pygame
Pygame is totally dependent on Python. We hope Python is already available on your system, and if you do not have it, first install the latest version of Python. Pygame is a cross-platform set of Python modules designed for composing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. The given command instals the pygame using the pip tool.
pip install pygame
Import required modules
In Python, all the necessary modules of the project need to be imported at the top. We have included the following modules for the snake game development and initialised the pygame using the pygame.init() method.
import pygame, time, random
pygame.init()
…….
…..
pygame.quit()
quit()
Finally, we need to uninitialised everything. So, we have used the quit() method at the end of the code.
Create the screen and set caption
The pygame.display.set_mode() function is used to create the screen surface and return the surface object. The set_mode() function accepts two arguments width and height of the window, and pygame.display.set_caption() function sets the window screen caption.
width = 700
height = 500
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Python Snake Game by Etutorialspoint')
Define the Clock
The pygame.time.Clock() function helps us to create an object for tracking time.
clock = pygame.time.Clock()
Create the snake
We have used the pygame.draw.rect() method to draw the rectangle that represents the snake. It doubles every time with the new score. The '[x[0], x[1], snake_block, snake_block]' defines the position and dimension of the snake.
snake_color = (0, 0, 0)
snake_block = 10
def snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, snake_color, [x[0], x[1], snake_block, snake_block])
Move the snake
To move the snake, we need key input from the user. The pygame KEYDOWN class gets the event when the keyword buttons are pressed. The events that we have used here are K_LEFT, K_RIGHT, K_UP, and K_DOWN. These keys represent the arrow keys to move the snake left, right, up and down.
while game_close == True:
game_over = False
game_close = False
x1 = width / 2
y1 = height / 2
x1_move = 0
y1_move = 0
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_move = -snake_block
y1_move = 0
elif event.key == pygame.K_RIGHT:
x1_move = snake_block
y1_move = 0
elif event.key == pygame.K_UP:
y1_move = -snake_block
x1_move = 0
elif event.key == pygame.K_DOWN:
y1_move = snake_block
x1_move = 0
Game Over: when users hit the boundaries
When the snake hits any boundary of the window, the user loses the game. For this, we have defined a variable game_close. When it is set to TRUE, it asks you to either play again or quit the game.
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
while game_close == True:
screen.fill(green)
message("You Lost The Game! Press A to Play Again OR Q to Quit", red)
total_score(snake_length - 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_a:
main()
Create snake food
We have created the snake food using the pygame.draw.circle() method and defined it in a function draw_food. The x and y attributes are the position of the food.
def draw_food(x, y, radius):
pygame.draw.circle(screen, food_color, [int(x), int(y)], radius)
Increasing the length of the snake
We have increased the size of the snake when it eats food. The variable snake_length contains the length of the snake, and snake_list contains the coordinates of the snake. We have defined a new list, snake_head which will be appended to the snake_list to increase the snake length.
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
snake(snake_block, snake_list)
total_score(snake_length - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
snake_length += 1
Define message
Here, we have defined a message to display when the game over.
# Display message when Game Over
def message(msg, color):
mesg = msg_font.render(msg, True, color)
screen.blit(mesg, [width / 10, height / 3])
Complete Code: Python snake game with pygame
Above, we have explained the snake game code in chunks. Here, we have merged them all to get the complete code.
import pygame, time, random
pygame.init()
score_color = (8, 6, 154)
snake_color = (0, 0, 0)
red = (213, 50, 80)
green = (4, 216, 2)
food_color = (218, 93, 0)
width = 700
height = 500
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Python Snake Game by Etutorialspoint')
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
msg_font = pygame.font.SysFont("Courier", 20)
score_font = pygame.font.SysFont("Times New Roman", 30)
# Draw Snake
def snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, snake_color, [x[0], x[1], snake_block, snake_block])
# Get Total Score
def total_score(score):
value = score_font.render("Total Score: " + str(score), True, score_color)
screen.blit(value, [0, 0])
# Display message when Game Over
def message(msg, color):
mesg = msg_font.render(msg, True, color)
screen.blit(mesg, [width / 10, height / 3])
# Draw Food
def draw_food(x, y, radius):
pygame.draw.circle(screen, food_color, [int(x), int(y)], radius)
# Main Game Loop
def main():
game_over = False
game_close = False
x1 = width / 2
y1 = height / 2
x1_move = 0
y1_move = 0
snake_list = []
snake_length = 1
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10
while not game_over:
while game_close == True:
screen.fill(green)
message("You Lost The Game! Press A to Play Again OR Q to Quit", red)
total_score(snake_length - 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_a:
main()
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_move = -snake_block
y1_move = 0
elif event.key == pygame.K_RIGHT:
x1_move = snake_block
y1_move = 0
elif event.key == pygame.K_UP:
y1_move = -snake_block
x1_move = 0
elif event.key == pygame.K_DOWN:
y1_move = snake_block
x1_move = 0
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
x1 += x1_move
y1 += y1_move
# Fill Screen Background
screen.fill(green)
draw_food(foodx, foody, 6)
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
snake(snake_block, snake_list)
total_score(snake_length - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
quit()
# Call Main Game Loop
main()
When, you will run the above code, it returns the following -
Related Articles
Convert list to dictionary PythonDictionary inside list Python
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python add list to list
Python Pandas Dataframe to CSV
Python compare two lists
Remove element from list Python
Python JSON Tutorial - Create, Read, Parse JSON file
How to draw different shapes using Python Pygame
Python send mail to multiple recipients using SMTP server
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml