NGF COLLEGE OF ENGINEERING AND TECHNOLGY
PAWAL
Project:Snake
Game
Submitted By: Submitted To:
Arman Malik Ankit Gupat
Roll no:
s18cse006
I am sure everybody has played the famous snake game. As a matter of fact, it was
one of the first mobile games that came into the market. Wouldn’t it be cool to build it
by yourself? Hell Yeah! In this article, I am going to use Python’s Turtle Module to
build it from scratch.
Agenda:
What Is Python’s Turtle Module?
Start Building The Game
o Set Up The Screen
o Create Snake’s Head
o Functions To Move The Snake
o Add Some Food
o Build Snake’s Body
o Add Border Collisions
o Add Body Collisions
o Add Scores
What Is Python’s Turtle Module?
I’m sure everybody has used a drawing board as a kid. Now, imagine, instead of
manually drawing on the board, you could command the system to draw for you. Isn’t
that cool? Python’s turtle module lets you do that. It basically lets you create a
drawing board and command a turtle to draw for you.
Have a look at the following basic python programming blogs to understand this blog
better:
Python Tutorial – A Complete Guide to Learn Python Programming
Programming With Python Tutorial
Python Programming Language – Headstart With Python Basics
Let’s move ahead and start building the game. I have used vscode with Python
version 2.7 for this article.
Start Building The Game
Let’s understand this game before we start building. There are two elements in this
game – snake and food. The player has to move the snake such that it touches(eats)
the food and grows in size. The snake dies if it touches its own body or the
boundaries of the window. On an obvious note, the player needs to win and hence
avoid dying.
Set Up the Screen
To start using the module, you need to import it like any other module in python.
Import turtle
The function turtle.Screen() is used to create a window. In this case, our window
is win for the game. Give this window a name with the function window.
Title(“Kalgi’s Snake Game”). Set the background color for the window with the
function window.bgcolor(“Color”). Set the window height and width with the
function window.setup (width=X, height=Y). The function window.tracer() turns
off the screen updates. We do not need any screen updates other than the
scoreboard and hence set to 0.
s=turtle.screen()
s.title("snake game")
s.bgcolor("gray")
s.setup(width=600,higestHighest=600)
#snake food
food=turtle.Turtle ()
food.speed (0)
food.shape("square")
food. Color("yellow")
food.goto(0,200)
food.st ()
Create Snake’s Head
Once you’ve created the window, the next thing we need is a snakehead. Snake is
basically a turtle(in python language) that moves around. Create a turtle with the
function turtle.Turtle() and assign it the name head. We set the head speed to 0 as
we’re just initializing in this section and the head does not need to move. We use the
function turtle_name.speed() for this. Next, we need to initialize the head shape and
color. We use the functions turtle_name.shape() and turtle_name.color().
Do we need to draw the paths taken by the snake? No! The
function turtle_name.penup() makes sure that the path taken by the snake is not
drawn. I want my snakehead’s position to be the center of the window and the
direction to be “stop”. We use the
functions turtle_name.goto() and turtle_name.direction() for it.
#create snake head
head=turtle.Turtle()
head=speed(0)
head=shape("square")
head.color("white")
head.fillcolor("blue")
head.penup()
head.goto(0,0)
head.direction="stop"
Once the head is created, I need a main game loop which is always set to true. I am going to
update my window using the function window.update(). This function basically updates my
screen continuously with the loop.
#main loop
while Ture:
s.update()
Functions To Move the Snake
Now that we have created a snake lets go ahead and make the snake move. We
define a function called move (). If the head goes up, the ‘y’ coordinate is increased,
if the head goes down, the ‘y’ coordinate decreases, if the head moves right, the ‘x’
coordinate increases and if the head moves left, the ‘x’ coordinate decreases.
def move():
if head.direction=="up"
y=head.ycor()
head.sety(y+20)
if head.direction=="down"
y=head.ycor()
head.sety(y-20)
if head.direction=="left"
y=head.ycor()
head.sety(y-20)
if head.direction=="right"
y=head.ycor()
head.sety(y+20)
The function does nothing until it’s called. So we need to call the function everytime we
update the screen or the window. Update the main game loop as follows:
#Main Game Loop
while: True
win.update()
move()
You can try executing the code so far and you’ll notice that the snake moves but very
fast. That’s the default behavior for the move function. To slow this down, we need to
use the time module. Go to the import section of your code and import the time
module. We initialize a variable called delay to 0.1. And then call the
function time.sleep(delay) to reduce turtle speed.
import turtle
import time
delay=0.1
# Main game loop
while True:
wn.update()
move()
time.sleep(delay)
We’ve made the functions for moving the turtle up, down, left and right. But how
does the computer know what up, down, left and right is? We need to define a
function for each of these directions and set
the head.direction to up, down, right and left.
Note: The snake cannot go right from left, left from right, top from down and down
from the top.
We need the system to listen to our control key presses. We add a function
called win.listen() that listens to the key presses. Every keypress needs to be bound to a
function that carries out an action. We use the function win.onkeypress(function,
“key”) for the same.
#event handling - key mapping
s.listen()
s.onkey(moveup,"up")
s.onkey(movedown,"down")
s.onkey(moveleft,"left")
s.onkey(moveright,"right")
s.onkey(movestop,"space")
Add Some Food
Food again is a turtle that remains
stationary until it’s been touched(eaten). Once the snake eats the food, it takes up
another random position and the game continuous. Let’s go ahead and create a
turtle for food in a similar way. We are going to use the same functions as we used
for creating the snakehead.
#snake food
food=turtle.Turtle()
food.speed(0)
food.shape("square")
food.color("yellow")
food.goto(0,200)
food.st()
Now that we’ve created the snakehead and the food and given functionalities to move, the
snake is suppossed to eat the food when it touches it and the food needs to take up a new
position. I am going to calculate the distance between the two objects with the
function head.distance(food). If the distance is less than 15(food and head come in
contact), the food is re-positioned to a random position anywhere within the window. Let’s go
ahead and add this feature in the main game loop.
if head.xcor()>290:
head.setx(-290)
if head.xcor()<-290:
head.setx(290)
if head.xcor()>290:
head.setx(-290)
if head.xcor()<-290:
head.setx(290)
Build Snake’s Body
Now we need a functionality that increases the snake body every time it touches
food. We use arrays for this purpose. We create an array called segments, which is
initialized to empty.
segments = []
We need to add a segment to the snake’s body everytime it touches the food. We
already have a condition that checks for the head’s collision with food. Create a new
turtle and name it new_segment, define its speed, shape, and color and append it to
the segments array.
body=turtle.Turtle()
body.speed(0)
body.penup()
body.shape("square")
body.color("red")
body.fillcolor("black")
bodies.append(body)
Add Border Collisions
We need to make sure that the snake dies when it collides with the border. We
already have the coordinates of the border, we just need to reset the snakehead
position when it touches those coordinates. Also, the snake needs to stop moving
and hence change the direction to stop.
for body in bodies:
if body.distance(head)<20:
time.sleep(1)
head.goto(0,0)
head.direction="stop"
Also, the segments need to disappear when the snake dies. For this, all we need to do is,
set the segment’s position outside the window coordinates. Now when the game restarts we
need fresh new segment and hence clear the segment list.
for body in bodies:
body.ht()
bodies.clear()
score=0
delay=0.1
#update score board
sb.clear()
sb.write("score: {} Highest score:
{}".format(score,highestscore))
time.sleep(delay)
And Tadaaaaa!! Your game is ready. Python is a widely-used programming
language with 8.2 million developers working with it. You’ll be surprised to see what
wonders it can do. Another cool module that allows you to develop games
is Pygame.
I hope this Python’s turtle module has helped you get an idea of how games can be
built with it. Please do use it to build more such games and let me know in the
comments section below. I’d love to play them.
Whole code for snake game :-
import turtle
import random
import time
delay=0.1
score-0
higestHighestestscore=0
#snake bodies
bodies=[]
#getting a screen \ canvas
s=turtle.screen()
s.title("snake game")
s.bgcolor("gray")
s.setup(width=600,higestHighest=600)
#create snake head
head=turtle.Turtle()
head=speed(0)
head=shape("square")
head.color("white")
head.fillcolor("blue")
head.penup()
head.goto(0,0)
head.direction="stop"
#snake food
food=turtle.Turtle()
food.speed(0)
food.shape("square")
food.color("yellow")
food.goto(0,200)
food.st()
#score board
sb=turtle.Turtle()
sb.shape("square")
sb.fillcolor("black")
sb.penup()
sb.ht()
sb.goto(-250,250)
sb.write("score:0 | Highest score: 0")
def moveup():
if head.direction!="down":
head.direction="up"
def movedown():
if head.direction!="up":
head.direction="down"
def moveleft():
if head.direction!="right"
head.direction="left"
def moveright():
if head.direction!="left"
head.direction="right"
def movetop():
head.direction="stop"
def move():
if head.direction=="up"
y=head.ycor()
head.sety(y+20)
if head.direction=="down"
y=head.ycor()
head.sety(y-20)
if head.direction=="left"
y=head.ycor()
head.sety(y-20)
if head.direction=="right"
y=head.ycor()
head.sety(y+20)
#event handling - key mapping
s.listen()
s.onkey(moveup,"up")
s.onkey(movedown,"down")
s.onkey(moveleft,"left")
s.onkey(moveright,"right")
s.onkey(movestop,"space")
#main loop
while Ture:
s.update()#this is to update the screen
#check the collosion with border
if head.xcor()>290:
head.setx(-290)
if head.xcor()<-290:
head.setx(290)
if head.xcor()>290:
head.setx(-290)
if head.xcor()<-290:
head.setx(290)
#check collosion with food
if head.distance(food)<20:
#move the food to new random place
x=random.randint(-290,290)
y=random.randint(-290,290)
food.goto(x,y)
#increase the length of the snake
body=turtle.Turtle()
body.speed(0)
body.penup()
body.shape("square")
body.color("red")
body.fillcolor("black")
bodies.append(body) #append the body
#increase the score
score+=10
#change delay
delay-=0.001
#update the higestHighest score
if score>highestscore:
highestscore=score
sb.clear()
sb.write("score:{} Highest: {}".format(score,highestscore))
#move the snake bodies
for inex in range(len(bodies)-1,0,-1):
x=bodies[index-1].xcor()
y=bodies[index-1].ycor()
bodies[index].goto(x,y)
if len(bodies)>0:
x=head.xcor()
y=head.ycor()
bodies[0].goto(x,y)
move()
#check collision with snake body
for body in bodies:
if body.distance(head)<20:
time.sleep(1)
head.goto(0,0)
head.direction="stop"
#hide bodies
for body in bodies:
body.ht()
bodies.clear()
score=0
delay=0.1
#update score board
sb.clear()
sb.write("score: {} Highest score: {}".format(score,highestscore))
time.sleep(delay)
s.mainloop()
#this is the end of our game
The Benefits
Did you know that Snake has some more practical/educational uses than just a way
to fill time?
Snake is a classic game that requires players to assess their surroundings and
find the quickest or safest route to a point. This is an excellent opportunity
to learn about spatial awareness and plan ahead to your next move.
The classic game is infamous for using your own success against you when
you become so long that you get in your own way. Whilst many games and
activities can teach your child about vital life skills, there are not many that
would educate on long term strategic planning.
As many parents will know, it can be extremely frustrating to reach such a
high level and then lose as you crash into your own tail. The game requires
patience in order to grow and a cool head once you inevitably lose. These
are all valuable skills to learn early on in a child’s life that will benefit them
in later years.
Snake is a tool that can be used as an educational helping hand. One of the
important parts of learning is that you will never get something right the first
time. Snake teaches children that practice makes perfect when it comes to
learning new skills.
THANKS