简体   繁体   中英

Python Turtle code seems to be in an infinite loop

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
    

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

If you use while true your code will be infinite because there is nothing telling the while loop when to stop.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM