1) What do I need to do?
π― Your mission: Make the snake move and steer
Make a head turtle and a game_loop function that moves it forward and uses screen.ontimer to run again.
Write 4 functions (up, down, left, right) that use setheading, and connect them to the arrow keys with screen.onkey.
Don't forget screen.listen() and turtle.done() at the end!
2) What do I need to know?
The game loop
Every arcade game has a game loop: a function that runs again and again, very fast.
Each time it runs it: 1. moves things, 2. checks for crashes, 3. sets a timer to run again.
screen.ontimer(game_loop, 100) means: run game_loop again in 100 milliseconds (a tenth of a second).
screen.tracer(0) turns off slow drawing, and screen.update() shows the new picture all at once β no flicker!
π§° Your toolkit for this mission
Everything you need to know to finish this lesson on your own:
Keys + timer
Arrow keys steer; screen.ontimer keeps the snake moving.
How to write it: Make one function per key with setheading, connect with screen.onkey.
screen.onkey(up, "Up") screen.listen()
Eating food
When the head is close to the food, score and move the food.
How to write it: if head.distance(food) < 20: then food.goto(...).
Lists for the body
Store body segments in a list and .append() a new one when you eat.
How to write it: Loop through the list to move each segment.
segments = [] segments.append(new_part)
Walls
Game over when the head leaves the screen.
How to write it: Check head.xcor() and head.ycor() with > and <.
if head.xcor() > 290 or head.xcor() < -290:
print("Game over!")global
Needed to change score inside a function.
How to write it: global score as the first line of the function.
Think about it
Look at this code. What happens next, and why? Say it in your own words.
screen.tracer(0) screen.update()
Watch & explore βΆ
Power-up: The game loop
See it happen
1 / 3def game_loop():
head.forward(20)A game loop moves things, checks for crashes, then runs again.
3) Run the code & terminal output
Press βΆ RUN and your program's messages appear here!


Captain Py
Our next adventure is yours to create.
