Snake Game Mini Project in Python(Turtle) with Source Code
Contents
Introduction
The Logo programming language is frequently linked to turtle graphics. In the late 1960s, Seymour Papert added turtle graphics support to Logo to support his version of the turtle robot, which is a simple robot controlled from the user’s workstation and designed to carry out the drawing functions assigned to it using a small retractable pen set into or attached to the robot’s body.
The standard library of the Python programming language now contains a Turtle graphics module. Turtle in Python, like its Logo ancestor, allows programmers to manipulate one or more turtles in a two-dimensional space.
Overview of the syntax
A location, an orientation (or direction), and a pen are the three qualities of the turtle. Color, width, and on/off state are all properties of the pen (also called down and up).
“Move ahead 10 spaces” and “turn left 90 degrees” are orders that the turtle responds to based on its current location. The turtle’s pen can also be managed by enabling it, changing its color, and adjusting its breadth. By visualizing what they would do if they were the turtle, a pupil may comprehend (and forecast and reason about) the turtle’s motion. This is referred to as “body syntonic” reasoning by Seymour Papert.
Basic syntax:
import turtle // start of the program
//body
//of the main
//code
turtle.done() //end of the program
Inorder to understand the codes to draw various shapes given below, Getting Started with Powerful yet Easy Python Graphics Module, Turtle.
Methods
Python is an object-oriented programming language, as we all know. This implies it can simulate the real world using classes and objects. A Python method is a label that can be applied to an object and is a piece of code that may be run on that object. But before we go any further, let’s have a look at some classes and objects.
A Python method is a label that can be applied to an object and is a piece of code that may be run on that object.
The most frequently, used turtle methods are:
Method | Parameter | Description |
---|---|---|
Turtle() | None | Creates and returns a new turtle object |
forward() | amount | Moves the turtle forward by the specified amount |
backward() | amount | Moves the turtle backward by the specified amount |
right() | angle | Turns the turtle clockwise |
left() | angle | Turns the turtle counterclockwise |
penup() | None | Picks up the turtle’s Pen |
pendown() | None | Puts down the turtle’s Pen |
up() | None | Picks up the turtle’s Pen |
down() | None | Puts down the turtle’s Pen |
color() | Color name | Changes the color of the turtle’s pen |
fillcolor() | Color name | Changes the color of the turtle will use to fill a polygon |
heading() | None | Returns the current heading |
position() | None | Returns the current position |
goto() | x, y | Move the turtle to position x,y |
begin_fill() | None | Remember the starting point for a filled polygon |
end_fill() | None | Close the polygon and fill with the current fill color |
dot() | None | Leave the dot at the current position |
stamp() | None | Leaves an impression of a turtle shape at the current location |
shape() | shapename | Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’ |
Python Turtle Snake Game Mini Project
The best way to learn is to do. Hence, what better way to learn python programming language (if you know the basics) than to code your first mini project. For this blog we are going to build a snake game mini project using python programming language. This is a python turtle snake game mini project
We all know snake game is a classic. On a bounded plane or surface or game screen, the player controls a dot, square, or object. It creates a trail behind it as it goes forward, mimicking a snake. In certain games, the trail’s terminus is set in stone, causing the snake to grow longer as it goes.
The keyboard keys are used to control the snake’s head. The orientation of the head is changed by pressing the left arrow key, which points East, Left, West, Up, North, and Down. Until an arrow key is clicked to change the direction of the head, it continues to move in the same way.
# import turtle, time and random module
import turtle
import time
import random
delay = 0.1
#scores
score = 0
high_score = 0
#set up screen
window = turtle.Screen()
window.title("Snake Game made by ABK for follow tuts")
window.bgcolor('green')
window.setup(width=600, height=600)
window.tracer(0)
#snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
head.goto(0,0)
head.direction = "stop"
# snake apple / food
apple= turtle.Turtle()
apple.speed(0)
apple.shape("circle")
apple.color("red")
apple.penup()
apple.goto(0,100)
segments = []
#scoreboards
sc = turtle.Turtle()
sc.speed(0)
sc.shape("square")
sc.color("black")
sc.penup()
sc.hideturtle()
sc.goto(0,260)
sc.write("score: 0 High score: 0", align = "center", font=("ds-digital", 24, "normal"))
#Functions
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
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":
x = head.xcor()
head.setx(x-20)
if head.direction == "right":
x = head.xcor()
head.setx(x+20)
#keyboard bindings
window.listen()
window.onkeypress(go_up, "Up")
window.onkeypress(go_down, "Down")
window.onkeypress(go_left, "Left")
window.onkeypress(go_right, "Right")
#MainLoop
while True:
window.update()
#check collision with border area
if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
#hide the segments of body
for segment in segments:
segment.goto(1000,1000) #out of range
#clear the segments
segments.clear()
#reset score
score = 0
#reset delay
delay = 0.1
sc.clear()
sc.write("score: {} High score: {}".format(score, high_score), align="center", font=("ds-digital", 24, "normal"))
#check collision with apple
if head.distance(apple) <20:
# move the apple to random place
x = random.randint(-290,290)
y = random.randint(-290,290)
apple.goto(x,y)
#add a new segment to the head
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("black")
new_segment.penup()
segments.append(new_segment)
#shorten the delay
delay -= 0.001
#increase the score
score += 10
if score > high_score:
high_score = score
sc.clear()
sc.write("score: {} High score: {}".format(score,high_score), align="center", font=("ds-digital", 24, "normal"))
#move the segments in reverse order
for index in range(len(segments)-1,0,-1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x,y)
#move segment 0 to head
if len(segments)>0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x,y)
move()
#check for collision with body
for segment in segments:
if segment.distance(head)<20:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
#hide segments
for segment in segments:
segment.goto(1000,1000)
segments.clear()
score = 0
delay = 0.1
#update the score
sc.clear()
sc.write("score: {} High score: {}".format(score,high_score), align="center", font=("ds-digital", 24, "normal"))
time.sleep(delay)
wn.mainloop()
Output
The following is the output for the above code for our python turtle snake game mini project.
- Output Screenshot 1:
- Output Screenshot 2: