简体   繁体   English

Python 海龟代码似乎在无限循环中

[英]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.也许while部分是问题,但我不知道如何解决它。 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您忘记为屏幕添加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

If you use while true your code will be infinite because there is nothing telling the while loop when to stop.如果您使用 while true 您的代码将是无限的,因为没有什么告诉 while 循环何时停止。

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.此外, break function 将不起作用,因为您的循环是一段时间的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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