Python Snake Pause and Restart
Pause is a flag that freezes the game where it stands. Restart starts a fresh run without closing the window.
The paused flag
paused is a flag that starts as False. False means the game runs.
paused = FalseFlipping the flag
toggle_pause() flips paused with not. One press pauses and the next press resumes.
def toggle_pause():
global paused
paused = not pausedTwo new keys
The p key calls toggle_pause(). The r key calls reset_game() directly as its key function.
screen.onkey(toggle_pause, "p")
screen.onkey(reset_game, "r")The loop while paused
The loop skips the game steps while paused is True. It still redraws the window and sleeps on each pass.
while True:
screen.update()
if not paused:Example
import turtle
import time
import random
# 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"
# The food: one red circle on the board
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
# The body starts empty; the scores start at zero
segments = []
score = 0
high_score = 0
delay = 0.1
paused = False
# The pen writes the score at the top of the board
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
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)
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 new_food_spot():
x = random.randint(-14, 14) * 20
y = random.randint(-14, 14) * 20
food.goto(x, y)
def show_score():
pen.clear()
pen.write(f"Score: {score} High Score: {high_score}", align="center", font=("Courier", 20, "bold"))
def toggle_pause():
global paused
paused = not paused
def reset_game():
global score, high_score, delay
time.sleep(0.5)
head.goto(0, 0)
head.direction = "stop"
for segment in segments:
segment.hideturtle()
segments.clear()
if score > high_score:
high_score = score
score = 0
delay = 0.1
show_score()
new_food_spot()
show_score()
# The keyboard steers the snake
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")
screen.onkey(go_right, "Right")
screen.onkey(toggle_pause, "p")
screen.onkey(reset_game, "r")
# The game loop: redraw, step the game unless paused, wait, repeat
while True:
screen.update()
if not paused:
# The body follows: each segment takes the place of the one ahead
for index in range(len(segments) - 1, 0, -1):
x = segments[index - 1].xcor()
y = segments[index - 1].ycor()
segments[index].goto(x, y)
if len(segments) > 0:
segments[0].goto(head.xcor(), head.ycor())
move()
# Walls: the head left the board, so the run ends
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
reset_game()
# Self: the head ran into the body, so the run ends
for segment in segments:
if segment.distance(head) < 20:
reset_game()
break
# Eat: the head reached the food
if head.distance(food) < 20:
new_food_spot()
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
score = score + 10
if delay > 0.05:
delay = delay - 0.005
show_score()
time.sleep(delay)Key points
- paused is a flag for the pause state.
- False means the game runs and True means it waits.
- toggle_pause() flips paused with not.
- The p key calls toggle_pause().
- The r key calls reset_game() directly.
- The loop skips the follow, move, rule and eat steps while paused.
- The loop still redraws and sleeps while paused.
In this example, paused starts as False and toggle_pause() flips it with not. The p key calls toggle_pause() and the r key calls reset_game() directly. The loop runs the follow, move, rule and eat steps only when paused is False. The loop still calls update and sleeps while paused, so the window stays alive and the p key keeps working.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why does the loop still redraw and sleep while paused?