0

currently I am trying to code a snake game in Python using the turtle module. Right now I am having issues with detecting collision with the wall and the snake head.

from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time


def main():
    screen = Screen()
    screen.setup(width=600, height=600)
    screen.bgcolor("black")
    screen.title("Snake Game")
    screen.tracer(0)

    scoreboard = Scoreboard()
    scoreboard.display_score()

    snake = Snake()
    food = Food()

    screen.listen()
    screen.onkey(snake.up, "Up")
    screen.onkey(snake.down, "Down")
    screen.onkey(snake.left, "Left")
    screen.onkey(snake.right, "Right")

    still_playing = True
    while still_playing:
        screen.update()
        time.sleep(0.1)
        snake.move()

        # Detect collision with food.
        if snake.head.distance(food) < 15:
            food.refresh()
            scoreboard.increase_score()

        # Detect collision with wall.
        if snake.has_hit_wall():
            scoreboard.game_over()
            still_playing = False

    screen.exitonclick()


if __name__ == "__main__":
    main()

The window I create in the program is 600 x 600.

    def has_hit_wall(self):
    return self.head.xcor() > 280 or self.head.xcor() < -280 or self.head.ycor() > 280 or self.head.ycor() < -280

The function above is used to detect when the snake head hits the wall. It works only when I am hitting the right or bottom of screen. If I hit the top or left it executes too early and I am not sure as to why.

Picture of hitting top

Picture of hitting left

Picture of hitting right

Picture of hitting bottom

I am unsure why this happens as the coordinates are not different on any of the sides. I have tried making the coordinates bigger or smaller but it does not seem to be fixing the problem.

  • Without knowing what sets the `xcor` or `ycor` of `head` then there's no way we can know why this is happening. This is not a [mre]. We can only assume that what is happening is that the values are getting set before you expect them to; but you haven't indicated stepping through this in a debugger or doing any such steps on your own to try to solve this. If you don't know how to debug then I suggest [PyCharm](https://www.jetbrains.com/help/pycharm/debugging-your-first-python-application.html). – Random Davis Jul 26 '22 at 16:48
  • It's only one pixel difference. Change the `>` conditions for `>=`, leave the `<` as `<` and increase the value to 281. This happens because there's a pixel 0 that breaks symmetry between positive and negative coordinates. Imagine you have a 4x4 map. X coordinates will be `-1, 0, 1, 2` and you can see here how they are assymetric. Otherwise make a map with an odd number of pixels –  Jul 26 '22 at 16:48

0 Answers0