Python Snake The Game Loop
A game loop is a loop that draws a frame, moves the game, and repeats. This lesson runs that loop and steps the head to the right on each pass.
Two imports
Turtle draws the window and the head. Time gives the sleep call that paces the loop.
import turtle
import timeTurning off automatic drawing
A frame is one complete drawing of the window. Tracer(0) turns off automatic drawing, so the program controls each frame.
screen.tracer(0)One pass of the loop
Update draws one frame, and the head steps 20 to the right. Sleep then waits a tenth of a second before the next pass.
while True:
screen.update()
head.setx(head.xcor() + 20)
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)
# The game loop: redraw, step, wait, repeat
while True:
screen.update()
head.setx(head.xcor() + 20)
time.sleep(0.1)Key points
- Tracer(0) turns off automatic drawing by the screen
- Update draws one frame each time it runs
- Sleep(0.1) waits a tenth of a second between frames
- Each pass steps the head 20 to the right
In this example, the program opens the window and turns off automatic drawing with tracer(0). It places the white head at the centre. The loop then runs for ever. Each pass draws one frame with update. Each pass steps the head 20 to the right. Each pass waits a tenth of a second with sleep. The head keeps stepping until it slides off the edge.
Note
The head slides off the edge for now, and walls come in a later lesson
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why does the loop call screen.update() on every pass?