Python Snake Moving by Direction
Direction is a value that says which way the head should move next. This lesson stores that value on the head and moves the head by reading it on each pass of the loop.
Starting direction
This line stores the word right on the head itself. The head moves right until that value changes.
head.direction = "right"Moving by direction
Move reads head.direction and runs the one branch that matches. Each branch steps the head 20 in its direction.
def move():
if head.direction == "up":
head.sety(head.ycor() + 20)
if head.direction == "down":
head.sety(head.ycor() - 20)
if head.direction == "left":
head.setx(head.xcor() - 20)
if head.direction == "right":
head.setx(head.xcor() + 20)The loop calls move
Each pass draws one frame and then calls move. Sleep waits a tenth of a second before the next pass.
while True:
screen.update()
move()
time.sleep(0.1)Example
import turtle
import time
# The game window
screen = turtle.Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake")
screen.tracer(0)
# The snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "right"
def move():
if head.direction == "up":
head.sety(head.ycor() + 20)
if head.direction == "down":
head.sety(head.ycor() - 20)
if head.direction == "left":
head.setx(head.xcor() - 20)
if head.direction == "right":
head.setx(head.xcor() + 20)
# The game loop: redraw, move, wait, repeat
while True:
screen.update()
move()
time.sleep(0.1)Key points
- head.direction holds the current direction on the head itself
- Move reads head.direction on each pass of the loop
- Each matching branch steps the head 20 in that direction
- The stop value matches no branch, so the head stays still
- The program starts with direction right, so the head crawls right at once
In this example, the program opens the window and places the white head at the centre. It stores the direction right on the head. It defines move to read that direction and step the head 20 to the right. The loop draws a frame, calls move, and waits a tenth of a second on each pass. The head crawls right in single steps.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens when head.direction holds the value "stop"?