๐ŸŽ“ A1Learner
๐Ÿ”
0 of 18 lessons completed

Python Snake Wall Collision

Wall collision is the rule that ends the run when the head leaves the board. The board edge for the head centre is 290.

The wall check

The wall check reads the head position after the move. One step past the edge ends the run.

    # 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()

The reset function

reset_game() brings the game back to its start state. The short pause comes first.

def reset_game():
    global score
    time.sleep(0.5)
    head.goto(0, 0)
    head.direction = "stop"
    for segment in segments:
        segment.hideturtle()
    segments.clear()
    score = 0

Hiding the body

hideturtle hides each segment before the list is cleared. Clearing an empty list would leave old squares on screen.

    for segment in segments:
        segment.hideturtle()
    segments.clear()

Rules before food

The loop checks the walls before it checks the food. A dead snake does not eat.

    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()

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 score starts at zero
segments = []
score = 0


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 reset_game():
    global score
    time.sleep(0.5)
    head.goto(0, 0)
    head.direction = "stop"
    for segment in segments:
        segment.hideturtle()
    segments.clear()
    score = 0


new_food_spot()

# 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")

# The game loop: redraw, follow, move, check the rules, eat, wait
while True:
    screen.update()

    # 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()

    # 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

    time.sleep(0.1)

Key points

  • The board edge for the head centre is 290.
  • One step past 290 in any direction ends the run.
  • The wall check runs right after move() in the loop.
  • The wall check runs before the eat check.
  • reset_game() puts the head back in the centre.
  • reset_game() sets the direction to stop and the score to 0.

In this example, the game builds the window, the head, the food and the empty body from the earlier lessons. The loop follows with the body, then moves the head one step. The loop then checks the head position against 290 on all four sides. A position past the edge calls reset_game() before the eat check can run. reset_game() waits half a second, sends the head home and hides and clears the segments.

Note

global score is needed because reset_game() assigns to a variable from outside it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when the head centre goes past 290?