[英]Python Turtle code seems to be in an infinite loop
我想为海龟编写征服小行星的代码。 但是如果你运行代码,它就会陷入无限循环并且不起作用。 也许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
您忘记为屏幕添加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
如果您使用 while true 您的代码将是无限的,因为没有什么告诉 while 循环何时停止。
添加变量
running = True
那么你的循环可以是
while running:
随着时间的推移,您可以更改变量,以便您的循环可以停止或相反。 此外, break function 将不起作用,因为您的循环是一段时间的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.