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.
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.