Python Turtle 代码似乎陷入了无限循环

时间:2021-04-20 05:31:24

标签: python python-turtle

我想为海龟编写一个征服小行星的代码。但是如果你运行代码,它会陷入无限循环并且不起作用。也许while部分是问题所在,但我不知道如何解决。请帮帮我。

很抱歉发这么长的帖子,因为这是我第一次发帖。 我真的很想修复错误。谢谢。

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()

被认为是错误的代码:

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
    

3 个答案:

答案 0 :(得分:2)

您忘记为屏幕添加 update() 方法

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

答案 1 :(得分:1)

如果你使用 while true 你的代码将是无限的,因为没有什么告诉 while 循环何时停止。

答案 2 :(得分:0)

添加变量

running = True

那么你的循环就可以

while running:

随着时间的推移,您可以更改变量,以便您的循环可以停止或相反。 此外,break 函数将不起作用,因为您的循环有一段时间为真。