Reputation: 11
I want to make a code for turtles to conquer asteroids. But if you run the code, it falls into an infinite loop and doesn't work. Maybe the while part is the problem, but I don't know how to solve it. Please help me.
I'm so sorry for the long post because it's my first time posting. I really want to fix the error. Thank you.
import turtle
import random
import math
player_speed = 2
score_num = 0
player = turtle.Turtle()
player.color('blue')
player.shape('turtle')
player.up()
player.speed(0)
screen = player.getscreen()
ai1_hide = False
ai1 = turtle.Turtle()
ai1.color('blue')
ai1.shape('circle')
ai1.up()
ai1.speed(0)
ai1.goto(random.randint(-300, 300), random.randint(-300, 300))
score = turtle.Turtle()
score.speed(0)
score.up()
score.hideturtle()
score.goto(-300,300)
score.write('score : ')
def Right():
player.setheading(0)
player.forward(10)
def Left():
player.setheading(180)
player.forward(10)
def Up():
player.setheading(90)
player.forward(10)
def Down():
player.setheading(270)
player.forward(10)
screen.onkeypress(Left, "Left")
screen.onkeypress(Right, "Right")
screen.onkeypress(Up, "Up")
screen.onkeypress(Down, "Down")
screen.listen()
Code thought to be an error :
while True:
distance = math.sqrt(math.pow(player.xcor() - ai1.xcor(), 2) + math.pow(player.ycor() - ai1.ycor(), 2))
if distance <= 20:
ai1.hideturtle()
score.clear()
if ai1_hide == False:
score_num += 1
ai1_hide = True
ai1.goto(0, 0)
score.write('score : ' + str(scoreNum))
if ai1.isvisible() != True:
break
Upvotes: 1
Views: 194
Reputation: 9
Add a variable
running = True
Then your loop can be
while running:
Over time you can change the variable so your loop can stop or the opposite. Also, the break function won't work since your loop is a while true.
Upvotes: 0
Reputation: 375
You forgot to add update()
method for screen
while True:
distance = math.sqrt(math.pow(player.xcor() - ai1.xcor(), 2) + math.pow(player.ycor() - ai1.ycor(), 2))
if distance <= 20:
ai1.hideturtle()
score.clear()
if ai1_hide == False:
score_num += 1
ai1_hide = True
ai1.goto(0, 0)
score.write('score : ' + str(scoreNum))
if not ai1.isvisible(): # boolean condition can also be simplified.
break
screen.update() # ADD this to your code
Upvotes: 3