Hello readers,
Today, I Am Going To Show You How We Can Create Simple Snake Game Using Python and Tkinter.
Introduction
readers, As we all already know that to make any skill sharp. we have to practice it as much as we can. so, if you are a new python programmer and searching for a practicing task that can help you in polishing your python programming skill then readers you came to a good site. basically, readers this python game script will boost your knowledge in both python OOP and Tkinter module. I know my some python examples look very hard for beginners but readers, believe me, my all example only look hard actually they are very easy to understand. The only reason they look hard because I am using OOP (Object Orient Programming). So, If you really want to be an expert Python programmer then don't lose your courage or guts.
How it's going to work?
Actually to make this game more easy to understand. here I am going to use Tkinter module. well, I know Tkinter is not good for gaming purpose but I am using it because it's very easy to use, easy to understand and also very powerful GUI module. so, now it's time to talk about the basic planning of snake game script code.
Basically, In this game, I am going to use Tkinter canvas widget as the ground for snake where the snake will scroll. The main reason behind using canvas widget is its powerful and wide range of shape representation facilities. In simple words, Tkinter canvas widget provides us the facility to represent various types of shape in different ways, In the different color, and with different configurations. hence with tkinter canvas widget, we don't need to worry about low-level functions & codings to make a snake game.
To make a running snake in canvas widget, I am going to use small rectangle shape available in canvas widget. basically, what I am going to do? is to make a snake coordinates list where I am going to save coordinates of snake body onto the canvas widget and whenever snake will move from one point to another, we will just update coordinates on list Basically, with snake coordinate list we will redraw snake shape every time again and again in every frame.
To capture keyboard input, we are going to use Tkinter built-in binding functions. With Tkinter binding class we can easily track keyboards output. actually for this game you need basic knowledge of python and Tkinter module because, without basic knowledge of Tkinter module this game is very difficult to understand so, I am assuming that you already aware with Tkinter module.
Now let's take a quick dive in python codes to understand what exactly I am going to do to make a snake game.
Requirements:
1. Tkinter (Built-In) Features:
1. Cross-Platform Support
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | #!/usr/bin/python # -*- coding: utf-8 -*- # # ---------------- READ ME --------------------------------------------- # This Script is Created Only For Practise And Educational Purpose Only # This is an Example Of Tkinter Canvas Graphics # This Script Is Created For http://www.bitforestinfo.com # This Script is Written By __author__='''
###################################################### By ######################################################
Suraj Singh surajsinghbisht054@gmail.com http://www.bitforestinfo.com/
###################################################### ''' print __author__ # ============= Configuration ================================== PLAYGROUND_WIDTH=700 PLAYGROUND_HEIGHT=400 PLAYGROUND_COLOR='powder blue' SNAKE_HEAD_COLOR="red" SNAKE_MOVING_SPEED=8
# ==============================================================
# Importing Modules try: import Tkinter except: import tkinter as Tkinter
import time, random
# Creating Main Function class main(Tkinter.Tk): def __init__(self, *args, **kwargs): Tkinter.Tk.__init__(self, *args, **kwargs) # Trigger Of Other Functions self.creating_playground() self.creating_snake_head() self.creating_snake_moving_settings() self.creating_score_board() self.bind('<Any-KeyPress>',self.connecting_head_with_keys)
# Creating Score Board def creating_score_board(self): self.scoreboard=Tkinter.Label(self, text="Score : {}".format(self.score)) self.scoreboard.pack(anchor='n') return # Updating Score Board def update_score_board(self): self.score=self.score+1 self.scoreboard['text']="Score : {}".format(self.score) #SNAKE_MOVING_SPEED=SNAKE_MOVING_SPEED+1 return # Creating Snake Moving Settings def creating_snake_moving_settings(self): self.x=SNAKE_MOVING_SPEED self.y=0 self.roadmap=[(0,0)] self.bodylength=3 self.snake_target=None self.gamevalid=1 self.score=0 return # Creating Snake Moving Head def connecting_head_with_keys(self, event=None): key=event.keysym if key=='Left': self.turn_left() elif key=='Right': self.turn_right() elif key=='Up': self.turn_up() elif key=='Down': self.turn_down() else: pass return # Creating Turning Function def turn_left(self): self.x=-SNAKE_MOVING_SPEED self.y=0 return # Creating Turning Function def turn_right(self): self.x=SNAKE_MOVING_SPEED self.y=0 return # Creating Turning Function def turn_up(self): self.x=0 self.y=-SNAKE_MOVING_SPEED return # Creating Turning Function def turn_down(self): self.x=0 self.y=SNAKE_MOVING_SPEED return # Creating snake Head def creating_snake_head(self): self.snake=self.board.create_rectangle(1,1,11,11,fill=SNAKE_HEAD_COLOR) return # Creating Ground def creating_playground(self): self.board=Tkinter.Canvas(self, width=PLAYGROUND_WIDTH, height=PLAYGROUND_HEIGHT, background=PLAYGROUND_COLOR) self.board.pack(padx=10, pady=10) return # Function For Moving Head def moving_snake_head(self): self.board.move(self.snake,self.x,self.y) x1,y1,x2,y2=self.board.coords(self.snake) if x1<=0 or y1<=0: self.x=0 self.y=0 self.game_loss() elif PLAYGROUND_HEIGHT<=y2 or PLAYGROUND_WIDTH<=x2: self.x=0 self.y=0 self.game_loss() return # Game Loss def game_loss(self): self.board.create_text(PLAYGROUND_WIDTH/2,PLAYGROUND_HEIGHT/2,text="Game Over"\ ,font=('arial 60 bold'),fill='red') self.gamevalid=0 return # Snake Regularly Moving def re_update(self): self.moving_snake_head() self.update_snake_body_structure() self.food_of_snake() return # Snake Food def food_of_snake(self): if self.snake_target==None: x1=random.randint(15,PLAYGROUND_WIDTH-15) y1=random.randint(15,PLAYGROUND_HEIGHT-15) self.snake_target=self.board.create_oval(x1,y1,x1+10,y1+10,fill='yellow', tag="food") if self.snake_target: x1,y1,x2,y2=self.board.coords(self.snake_target) if len(self.board.find_overlapping(x1,y1,x2,y2))!=1: self.board.delete("food") self.snake_target=None self.update_score_board() return # Creating Snake Body Moving Function def update_snake_body_structure(self): x1,y1,x2,y2=self.board.coords(self.snake) x2=(x2-((x2-x1)/2)) y2=(y2-((y2-y1)/2)) self.roadmap.append((x2,y2)) self.board.delete('body') if len(self.roadmap)>=self.bodylength: self.roadmap=self.roadmap[-self.bodylength:] self.board.create_line(tuple(self.roadmap), tag="body",width=10,fill=SNAKE_HEAD_COLOR) return
# Script Trigger if __name__ == '__main__': root=main(className=" Snake Game ") while True: root.update() root.update_idletasks() root.re_update() time.sleep(0.09)
|
If Anyone Wants To Download Then
Click hereScreenShots:Cool!
Example Code Explanations
Basic Structure of Our game# Creating Main Function
class main(Tkinter.Tk):
def __init__(self, *args, **kwargs):
Tkinter.Tk.__init__(self, *args, **kwargs)
# Trigger Of Other Functions
self.creating_playground()
self.creating_snake_head()
self.creating_snake_moving_settings()
self.creating_score_board()
self.bind('<Any-KeyPress>',self.connecting_head_with_keys)
# Script Trigger
if __name__ == '__main__':
root=main(className=" Snake Game ")
while True:
root.update()
root.update_idletasks()
root.re_update()
time.sleep(0.09)
1. Functions Responsible for creating shapes and widgets. # Creating Score Board
def creating_score_board(self):
self.scoreboard=Tkinter.Label(self, text="Score : {}".format(self.score))
self.scoreboard.pack(anchor='n')
return
# Creating Snake Moving Settings
def creating_snake_moving_settings(self):
self.x=SNAKE_MOVING_SPEED
self.y=0
self.roadmap=[(0,0)]
self.bodylength=3
self.snake_target=None
self.gamevalid=1
self.score=0
return
# Creating snake Head
def creating_snake_head(self):
self.snake=self.board.create_rectangle(1,1,11,11,fill=SNAKE_HEAD_COLOR)
return
# Creating Ground
def creating_playground(self):
self.board=Tkinter.Canvas(self, width=PLAYGROUND_WIDTH, height=PLAYGROUND_HEIGHT, background=PLAYGROUND_COLOR)
self.board.pack(padx=10, pady=10)
return
2. Functions Responsible For Providing Moving Facilities
# Updating Score Board
def update_score_board(self):
self.score=self.score+1
self.scoreboard['text']="Score : {}".format(self.score)
#SNAKE_MOVING_SPEED=SNAKE_MOVING_SPEED+1
return
# Creating Snake Moving Settings
def creating_snake_moving_settings(self):
self.x=SNAKE_MOVING_SPEED
self.y=0
self.roadmap=[(0,0)]
self.bodylength=3
self.snake_target=None
self.gamevalid=1
self.score=0
return
# Creating Snake Moving Head
def connecting_head_with_keys(self, event=None):
key=event.keysym
if key=='Left':
self.turn_left()
elif key=='Right':
self.turn_right()
elif key=='Up':
self.turn_up()
elif key=='Down':
self.turn_down()
else:
pass
return
# Creating Turning Function
def turn_left(self):
self.x=-SNAKE_MOVING_SPEED
self.y=0
return
# Creating Turning Function
def turn_right(self):
self.x=SNAKE_MOVING_SPEED
self.y=0
return
# Creating Turning Function
def turn_up(self):
self.x=0
self.y=-SNAKE_MOVING_SPEED
return
# Creating Turning Function
def turn_down(self):
self.x=0
self.y=SNAKE_MOVING_SPEED
return
# Function For Moving Head
def moving_snake_head(self):
self.board.move(self.snake,self.x,self.y)
x1,y1,x2,y2=self.board.coords(self.snake)
if x1<=0 or y1<=0:
self.x=0
self.y=0
self.game_loss()
elif PLAYGROUND_HEIGHT<=y2 or PLAYGROUND_WIDTH<=x2:
self.x=0
self.y=0
self.game_loss()
return
# Creating Snake Body Moving Function
def update_snake_body_structure(self):
x1,y1,x2,y2=self.board.coords(self.snake)
x2=(x2-((x2-x1)/2))
y2=(y2-((y2-y1)/2))
self.roadmap.append((x2,y2))
self.board.delete('body')
if len(self.roadmap)>=self.bodylength:
self.roadmap=self.roadmap[-self.bodylength:]
self.board.create_line(tuple(self.roadmap), tag="body",width=10,fill=SNAKE_HEAD_COLOR)
return
3. Function for responsible for snake food # Snake Food
def food_of_snake(self):
if self.snake_target==None:
x1=random.randint(15,PLAYGROUND_WIDTH-15)
y1=random.randint(15,PLAYGROUND_HEIGHT-15)
self.snake_target=self.board.create_oval(x1,y1,x1+10,y1+10,fill='yellow', tag="food")
if self.snake_target:
x1,y1,x2,y2=self.board.coords(self.snake_target)
if len(self.board.find_overlapping(x1,y1,x2,y2))!=1:
self.board.delete("food")
self.snake_target=None
self.update_score_board()
return
4 Function for regularly updating all other necessary movement-related functions. # Snake Regularly Moving
def re_update(self):
self.moving_snake_head()
self.update_snake_body_structure()
self.food_of_snake()
return
5. Configuration
# ============= Configuration ==================================
PLAYGROUND_WIDTH=700
PLAYGROUND_HEIGHT=400
PLAYGROUND_COLOR='powder blue'
SNAKE_HEAD_COLOR="red"
SNAKE_MOVING_SPEED=8
This tutorial Ends here,
I hope you enjoyed it.
For any question or Suggestion or helppost Comment below.