Python Snake Game – Create Snake Game Program

FREE Online Courses: Enroll Now, Thank us Later!

Snake game is one of the most popular game, since a long time when we used to have keypad phones.

The game is as easy to code as to play and in this article, we will develop snake game in python

We will use python to build the logic of the game and for the interface part, we will use tkinter because it is easy to use.

Project Prerequisites

The prerequisites are as follows: Basic concepts of Python, Tkinter

Download Snake Game Python Code

Please download source code of python snake game project: Snake Game Python Code

Creating Snake Game Program – main.py

from tkinter import *
import random,time

class Snake(Tk):
    def __init__(self,*arge,**kwargs):
        Tk.__init__(self,*arge,**kwargs)
        self.initialSetup()
        
    def initialSetup(self):
        self.base=Canvas(self,width=500,height=500)
        self.base.pack(padx=10,pady=10)
        self.snake=self.base.create_rectangle(1,1,21,21,fill="DodgerBlue2")
        self.score=0
        self.scoreDisplay=Label(self,text="Score:{}".format(self.score),font=('arial',20,'bold'))
        self.scoreDisplay.pack(anchor='n')
        self.length=3
        self.target=None
        self.gameStatus=1
        self.x=20
        self.y=0
        self.bodycoords=[(0,0)]    
        self.bind('<Any-KeyPress>',self.linkKeys)
        return

    def check_snake_coords(self):
        self.base.move(self.snake,self.x,self.y)
        i,j,ii,jj=self.base.coords(self.snake)
        if i<=0 or j<=0 or ii>=500 or jj>=500:
            self.x=0
            self.y=0
            #gameover
            self.base.create_text(220,220,text="GAME OVER",font=('arial',40,'bold'),fill='red')
            self.gameStatus=0
        return

    def move_snake(self):
        i,j,ii,jj=self.base.coords(self.snake)
        ii=(ii-((ii-i)/2))
        jj=(jj-((jj-j)/2))
        self.bodycoords.append((ii,jj))
        self.base.delete('snakebody')
        if len(self.bodycoords)>=self.length:
            self.bodycoords=self.bodycoords[-self.length:]
        self.base.create_line(tuple(self.bodycoords),tag='snakebody',width=20,fill="DodgerBlue2")
        return
        
    def food(self):
        if self.target==None:
            a=random.randint(20,480)
            b=random.randint(20,480)
            self.target=self.base.create_oval(a,b,a+20,b+20,fill='red',tag='food')
            #print(self.base.coords(self.target))
        if self.target:
            #print(self.base.coords(self.target))
            i,j,ii,jj=self.base.coords(self.target)
            #time.sleep(0.1)
            if len(self.base.find_overlapping(i,j,ii,jj))!=1:
                self.base.delete("food")
                self.target=None
                self.updateScore()
                self.length+=1
            return

    def updateScore(self):
        self.score+=1
        self.scoreDisplay['text']="Score : {}".format(self.score)
        return

    def linkKeys(self,event=None):
        pressedkey=event.keysym
        if pressedkey=='Left':
            self.x=-20
            self.y=0

        elif pressedkey=='Up':
            self.x=0
            self.y=-20

        elif pressedkey=='Right':
            self.x=20
            self.y=0

        elif pressedkey=='Down':
            self.x=0
            self.y=20

        else:
            pass
        return

    def manage(self):
        if(self.gameStatus==0):
            return
        self.check_snake_coords()
        self.move_snake()
        self.food()
        
        return

snakeobj=Snake(className="ProjectGurukul Snake Game")
while True:
    snakeobj.update()
    snakeobj.update_idletasks()
    snakeobj.manage()
    time.sleep(0.4)

As you can see in the above code we have created a snake class and there we have defined eight functions which are explained below:

1. __init__: This is the constructor function that calls initialSetup function and also it initializes the tkinter window.

2. initialSetup: This function creates all the variables like the snake, playground, score, and many more. We will use canvas for the playground area because canvas provides many inbuilt functions for creating shapes and it is recommended to use while developing games. Also, we will link the keys for snake movement by calling linkKeys function.

3. linkKeys: This function is responsible for changing the direction of the snake and for all four directions we have modified the coordinates accordingly.

4. Move_snake: This function is responsible for moving the snake body by moving its whole body by one block and deleting the last block.

5. food: This function generates a random x and y coordinate by calling random function to place the food at a random location on the playground and then it creates an oval shape denoting the fruit. And then it checks if the snake’s head overlaps with the food and if it does, it increases snake’s length by one and after that, it calls updateScore().

6. updateScore: It simply increases the score and then it displays the updated score.

7. check_snake_coords: This function checks if any coordinate of the snake lies outside the playground (i.e. less than 0 or greater than 500), and if it does, it will print “Game Over” on the playground and will set gameStatus to zero.

8. Manage: It is the most important function because it is responsible for calling food, move_snake, and check_snake_coords, the functions responsible for movement of the snake.

After definition of the Snake class, we have created its object ‘snakeobj’. And then we have an infinite while loop which updates snake and calls manage function after every 0.4 seconds.

Note: You can modify the sleeping time of the while loop to increase or decrease speed of the snake.

Python Snake Game Output

snake game output

Summary:

We have successfully completed python snake game project. Snake game is popular amongst children, but it’s also popular amongst the python developers to develop games in python.

2 Responses

  1. Abdelrahman Khaled Abdulmuniem Younis says:

    These is a very good project

  2. osama spinladen says:

    this is trash ui hope you lern to do bettr and i hope you get goood at video games

Leave a Reply

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