1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How can I program obstacles in a snake game? (Python 3 and Turtle graphics)

Discussão em 'Python' iniciado por Stack, Setembro 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to program a snake game with Turtle in Python 3 and so far everything has gone well, but now I have a problem. And my problem is that the snake just moves through the obstacles, although I want the game to restart as soon as the snake head hits one of the obstacles.

    And by the way, it is my first program so I hope that the answer to my question is not too obvious.


    Snake head

    head = turtle.Turtle()
    head.speed(0)
    head.shape("square")
    head.color("red")
    head.penup()
    head.goto(0, 0)


    Obstacles

    ob1 = turtle.Turtle()
    ob1.speed(0)
    ob1.shape("square")
    ob1.color("black")
    ob1.penup()
    ob1.goto(0, 100)
    ob1.shapesize(stretch_wid=1, stretch_len=20)

    ob2 = turtle.Turtle()
    ob2.speed(0)
    ob2.shape("square")
    ob2.color("black")
    ob2.penup()
    ob2.goto(0, -100)
    ob2.shapesize(stretch_wid=1, stretch_len=20)


    First I tried that:

    if head.distance(ob1) < 20 or head.distance(ob2) < 20:
    restart()


    But the problem with this is, that only one part of the obstacle will restart the game as soon as the snake touches that part but the rest of the obstacle poses no danger because the snake can easily move through this rest of the obstacle.

    And that's because the obstacles, despite their size, only occupy one field of the window, namely the field that I determined with ob1.goto (0, 100).


    And then I tried to make lists filled with the coordinates of the obstacles and then use these lists to compare the numbers they contain with the Y and X position of the snake's head:

    numbers = []

    y = range(-200, 200)
    for n in y:
    numbers.append(n)

    if head.ycor() == (numbers):
    restart()


    But still the snake could move through all of the obstacles.

    Continue reading...

Compartilhe esta Página