0
我正在用Python製作一款遊戲,其中一隻烏龜(稱爲Lewi)跟隨另一隻(稱爲Ella)。就目前而言,本場比賽的目標是Ella比Lewi略慢,應該跟隨Lewi。 Lewi按照箭頭鍵按下。如何讓Python龜停止試圖趕上它跟蹤的龜?
Ella確實跟隨Lewi,但問題是,如果你在Ella到達Lewi的位置之前按兩次或多次'right'鍵,然後讓她趕上他的位置,那麼她會開始回到她以前的所有位置,她沒能趕上Lewi,然後繼續前往她所錯過的所有Lewi職位。
艾拉不應該回溯她的步驟,那麼我該如何解決這個問題?這裏是代碼:
import turtle
image = "C:/Python27/Pythonprogramming/image.gif"
screenr = turtle.Screen()
Lewi = turtle.Turtle()
Ella = turtle.Turtle()
screenr.addshape(image)
Lewi.shape(image)
screenr.bgpic("winXP.gif")
screenr.setup(1279, 815)
Lewi.penup()
speed = 50
def up():
Lewi.sety(Lewi.ycor()+speed)
Ella.speed(1)
Ella.goto(Lewi.pos())
if Ella.pos() == Lewi.pos():
print("loo")
def down():
Lewi.sety(Lewi.ycor()-speed)
Ella.speed(1)
Ella.goto(Lewi.pos())
if Ella.pos() == Lewi.pos():
print("loo")
def left():
Lewi.forward(-speed)
Ella.speed(1)
Ella.goto(Lewi.pos())
if Ella.pos() == Lewi.pos():
print("loo")
def right():
Lewi.forward(speed)
Ella.speed(1)
Ella.goto(Lewi.pos())
if Ella.pos() == Lewi.pos():
print("loo")
screenr.onkey(up, "Up")
screenr.onkey(down, "Down")
screenr.onkey(right, "Right")
screenr.onkey(left, "Left")
screenr.listen()
turtle.mainloop()
我的埃拉一直走過我,嘿。 –
有一些我一直試圖平衡的錯誤。例如,Ella永遠不可能和Lewi坐在同一個座標上,因爲她指向一個角度朝向他,但卻以相同的「速度」移動。然而,這可以用矢量公式來修復。真正的問題在於,Lewi沒有像原始代碼那樣流暢,即如果這是在一場比賽中,那麼這將會讓人非常沮喪。它似乎是最好的工作解決方案,所以我會在找到解決方案時進行更新。如果你找到了解決方案,那麼請讓我看看。並謝謝順便說一句。 –
不,不要,只是想通了!你需要在代碼的開始處有這個'Lewi.speed(0)'(最好在定義Lewi之後)。這種情況下的「速度」是一個函數(速度()),不應與變量「速度」混淆。 –