我想做一个代码让海龟们征服小行星。但是如果你运行代码,它就会陷入无限循环而无法工作。也许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
发布于 2021-04-20 22:49:14
您忘记为屏幕添加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
发布于 2021-04-20 22:32:53
如果您使用while true,那么您的代码将是无限的,因为没有任何东西告诉while循环何时停止。
发布于 2021-06-21 14:36:32
添加一个变量
running = True
那么你的循环就可以
while running:
随着时间的推移,您可以更改变量,这样循环就可以停止,或者相反。此外,由于您的循环是while true,break函数将不起作用。
https://stackoverflow.com/questions/67172988
复制相似问题