簡體   English   中英

Python 海龜代碼似乎在無限循環中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM