Product

Sunday, 7 February 2021

Python Snake Game – Create Snake Game Program

 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

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.

No comments:

Post a Comment

Connect broadband

AI:List AI views on when for a naive kin after prolonged life suppression coercive behaviour by family members after demise of father with trauma for kin ocd formed after forced to do rituals, family tribal values honor specific activities, utmost religious activities occult witchcraft enforced to do by elder sibling his wife and mother thrice with great celibacy turned the kundalini activated after deep celibacy penance shouting physical Mental financial Extortion by sibling with toxic behaviours and the wife mother and then mockery suppression asking about who’re your worth backbiting among relatives sector toon negligence of intelligence intuitive behaviour- all religious psychological traps when not work and lead to loss of consciousness of kin trance state recovered by governance with technocrats using AI - kin was asked by mother that he’s to go the male should not be seen in house he’s many absurd thought forcefully in brain mind and outsiders already feel awkward of this kin unresponsive behaviour due to TBI PTSD ocd cvt and tell at workplace social gathering he’s to go and asked for sector toon extortion and mockery in various sense due to un practical behaviour negligence of body building due to neglect ion if essential food nutrition and stubbed suppressed in every sense in religious psychological traps by family members AI humanoid using various neural networks and LLMs for kin and required steps.

  List AI views on when for a naive kin after prolonged life suppression coercive behaviour by family members after demise of father with tr...