Python - Snake Game Using pygame Module
The snake game is one of the most ancient games which were introduced on arcade and accepted by generations of people who prefer playing. In this tutorial, we'll learn to develop a simple snake game with start screen, bordered play area and working snake.
Installations
First, you have to install pygame module. The pygame is a Python library that is used for developing games. You can install it using pip −
pip install pygame
Python Code to Design Snake Game
Here is the complete code to design snake game using pygame module −
import pygame
import time
import random
# Initialize Pygame
pygame.init()
# Define 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)
# Define display dimensions
dis_width = 800
dis_height = 600
# Create the display
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.setCaption('Snake Game by Souvik')
# Set the clock for controlling the game speed
clock = pygame.time.Clock()
# Define snake block size and speed
snake_block = 10
snake_speed = 15
# Define font style and size
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
# Function to display the score
def Your_score(score):
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])
# Function to draw the snake
def our_snake(snake_block, snake_List):
for x in snake_List:
pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
# Function to display message
def message(msg, color, position):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, position)
# Start screen
def start_screen():
start = True
while start:
dis.fill(blue)
message("Welcome to Snake Game", white, [dis_width / 6, dis_height / 3])
message("Press S to Start or Q to Quit", white, [dis_width / 6, dis_height / 2])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
quit()
if event.key == pygame.K_s:
start = False
if event.type == pygame.QUIT:
pygame.quit()
quit()
# The game loop
def gameLoop():
start_screen()
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
# Generate food coordinates
foodx = round(random.randrange(10, dis_width - snake_block - 10) / 10.0) * 10.0
foody = round(random.randrange(10, dis_height - snake_block - 10) / 10.0) * 10.0
while not game_over:
while game_close == True:
dis.fill(blue)
message("You Lost! Press C-Play Again or Q-Quit", red, [dis_width / 6, dis_height / 3])
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 - 10 or x1 < 10 or y1 >= dis_height - 10 or y1 < 10:
game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(blue)
# Draw the border
pygame.draw.rect(dis, white, [10, 10, dis_width - 20, dis_height - 20], 5)
# Draw the food
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
# Move the snake
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(10, dis_width - snake_block - 10) / 10.0) * 10.0
foody = round(random.randrange(10, dis_height - snake_block - 10) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
# Run the game
gameLoop()
Code Explanation
Some of the procedures used in developing the game are as follows −
- Initialize pygame − The basics, to begin with, one has to import pygame and then start it up with init().
- Set Up the Display − Clear the screen size and obtain the size of the window to be used in displaying the content.
- Define Colors and Fonts − Include all the colors that is to be used in the game and all the fonts to be used for the textual part of the game.
- Create the Start Screen − The start_screen() function prints a message to the console with information to the player starting soon and waits for the user’s input to begin the game.
- Game Loop − The gameLoop() function deals with the motion, check for collision, and scoring of points. It has logic that helps in controlling the snake, creation of the food and determination of when the game is over.
- Bordered Play Area − Since pygame is used here to design the play area, a white border is created around the area. draw. bend it as well so that the snake cannot escape the area that has been enclosed by the stick.
- End the Game − This continues till the snake hits the border or even the snake’s own tail; thus, the game is over. At the end of the game the player can decide to play the game again or quit.
Output
When you run the game, you'll start with a welcome screen prompting you to press 'S' to start the game or 'Q' to quit.
Once the game starts, the snake will move inside a bordered area. The goal is to eat the food (green block) and grow the snake while avoiding collisions with the walls or the snake's own body.
After game is over you can play again or quit option