Python Snake Game

Making a Python Snake Game is a big-time achievement for any Python Newbie Developer as this game will not only help you to use the basic knowledge that you’ve acquired while learning Python but also we have used some functions and build classes that will help guide you about few more important concepts in Python Programming!

So in this Game we are going to build something like what we have shown in the image below:

Python Snake Game

So to start making the Python snake Game we start by importing important stuff:

sys — To terminate the execution of this code

random — To randomly spawn food in the world

time — to keep the max number of frames in check

[cc type = ‘python’]

import pygame
import sys
import random
import time

[/cc]

Class snake is responsible for drawing and movement of the snake. Also to check if the snake is alive or has collided with the wall.

[cc type = ‘python’]

class Snake():
def __init__(self):
#position is the head postion of snake
self.position = [100,50]
#initialize snake with 3 blocks
self.body = [[100,50], [90,50], [80,50]]
self.direction = 'RIGHT' # initial direction of movement
self.changeDirectionTo = self.direction

def changeDirTo(self,dir):
# turning directly in opposite direction should not be allowed
if dir == 'RIGHT' and not self.direction == 'LEFT':
self.direction = 'RIGHT'
if dir == 'LEFT' and not self.direction == 'RIGHT':
self.direction = 'LEFT'
if dir == 'UP' and not self.direction == 'DOWN':
self.direction = 'UP'
if dir == 'DOWN' and not self.direction == 'UP':
self.direction = 'DOWN'

def move(self,foodPos):
# move 1 block in the specfied direction
if self.direction == 'RIGHT':
self.position[0] += 10
if self.direction == 'LEFT':
self.position[0] -= 10
if self.direction == 'UP':
self.position[1] -= 10
if self.direction == 'DOWN':
self.position[1] += 10
self.body.insert(0,list(self.position))
#if collide with food, increase size of snake
if self.position == foodPos:
return 1
else:
self.body.pop()
return 0

def checkCollision(self):
#check collision with walls
if self.position[0] > 490 or self.position[0] < 0:
return 1
if self.position[1] > 490 or self.position[1] < 0:
return 1
for bodyPart in self.body[1:]:
if self.position[0] == bodyPart[0] and self.position[1] == bodyPart[1]:
return 1
return 0

def getHeadPos(self):
return self.position

def getBody(self):
return self.body

[/cc]

FoodSpawner object spawns food when food is not on screen:

[cc type = ‘python’]

class FoodSpawner():
def __init__(self):
# spawn food randomly in the world space in the beginning
self.position = [random.randrange(1,50)*10,random.randrange(1,50)*10]
self.isFoodOnScreen = True

def spawnFood(self):
#spawn food if i's not there n the world
if self.isFoodOnScreen == False:
self.position = [random.randrange(1,50)*10,random.randrange(1,50)*10]
self.isFoodOnScreen = True
return self.position

def setFoodOnScreen(self,b):
self.isFoodOnScreen = b

[/cc]

To quit the game when snake dies, we use following functions:

pygame.quit() will kill the game GUI

while sys.exit() will terminate the script.

The code for the same is as follows:

[cc type = ‘python’]

def gameOver():
pygame.quit()
sys.exit()

[/cc]

We can create a window of 500px by 500px for this game, you can increase or decrease this a per your choice.

In this game, fps (a.k.a. frames per second) will keep track of the number of frames that are refreshed every second in the game. So for this, we will code as follows:

[cc type = ‘python’]

window = pygame.display.set_mode((500, 500))
pygame.display.set_caption("WoW Snake")
fps = pygame.time.Clock()
score = 0
snake = Snake()
foodSpawner = FoodSpawner()

[/cc]

Now to make the game go into an infinite loop, we will use the code as shown below:

[cc type = ‘python’]

while True:
# first we check for any input from user.
for event in pygame.event.get():
#if user exits the game quit
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#else if user presses direction key, set direction os snake
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.changeDirTo("RIGHT")
if event.key == pygame.K_LEFT:
snake.changeDirTo("LEFT")
if event.key == pygame.K_UP:
snake.changeDirTo("UP")
if event.key == pygame.K_DOWN:
snake.changeDirTo("DOWN")
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
#spawn food
foodPos = foodSpawner.spawnFood()
#move snake and check if it ate food and increase score accordingly
if(snake.move(foodPos)==1):
score = score+1
foodSpawner.setFoodOnScreen(False)
#now time to draw GUI. fill background with white color
window.fill(pygame.Color(225,225,225))
#draw snake body with Green color and food with red color
for pos in snake.getBody():
pygame.draw.rect(window, pygame.Color(0,225,0), pygame.Rect(pos[0],pos[1],10,10))
pygame.draw.rect(window, pygame.Color(225,0,0), pygame.Rect(foodPos[0],foodPos[1],10,10))
#if snake collided with wall, gamever
if(snake.checkCollision()==1):
gameOver()
pygame.display.set_caption("WoW Snake | Score : "+ str(score))
# update the game GUI
pygame.display.flip()
#limit frames per second o 24
fps.tick(24)

[/cc]

Ta Da! This is what you will end up after programming in Python and coding as shown below!