0

I was coding a turtle game where when the snake goes near the "apple", it goes to a random cord and we repeat. I tried to add a go to function in python but it is not moving for some reason. I added a check to see if the if statement is happening and it is, but after the check, nothing runs. What is the problem with my code?

import turtle as t


import random

wn=t.Screen()


t.shape("turtle")
t.pu()

apple=t.Turtle()

apple.pu()

apple.shape("circle")
apple.color("red")

def forw():
  t.forward(10)
def back():
  t.backward(10)


wn.onkey(forw,"Up")
wn.onkey(back,"Down")
wn.onkey(lambda: t.left(45),"Left")
wn.onkey(lambda: t.right(45),"Right")
wn.listen()

if t.distance(apple)<=15 or t.distance(apple)>=-15:
  print("check1")
  apple.goto(random.randint(-50,50),random.randint(-50,50))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 3
    Your program as written will just terminate. Add wn.mainloop() after wn.listen() – Amir Afghani Dec 25 '21 at 18:42
  • You are performing the distance check *exactly once*, as your program is starting up - the user has had no chance to actually move the snake yet. You need to perform the check after each move, in other words in both `forw()` and `back()`. (Ideally the check would be in a separate function called in both of those places, so you don't have to repeat the code.) – jasonharper Dec 25 '21 at 18:45
  • Also, comparing the distance to -15 is unneeded - the distance will always be a non-negative number. – jasonharper Dec 25 '21 at 18:48
  • Thanks everyone for all your help! I figured out the code and got it to work! – Midyan Goel Dec 25 '21 at 19:19
  • Feel free to post a [self answer](https://stackoverflow.com/help/self-answer) to help others with the same problem as you. – ggorlen Jan 13 '22 at 23:25

0 Answers0