2017-04-16 80 views
-1

我正在創建一個遊戲,用戶使用鍵盤移動龜以避免另一隻龜。這是我的代碼:使一個龜龜追逐另一隻海龜

import turtle 
playGround = turtle.Screen() 
playGround.screensize(500, 500) 
playGround.title("Turtle Keys") 

run = turtle.Turtle() 
follow = turtle.Turtle() 
run.shape("turtle") 
follow.shape("turtle") 
run.color("blue") 
follow.color("red") 
run.penup() 
follow.penup() 
run.st() 

def k1(): 
    run.forward(45) 
def k2(): 
    run.left(45) 
def k3(): 
    run.right(45) 
def k4(): 
    run.back(45) 
def quitThis(): 
    playGround.bye() 
playGround.onkey(k1, "Up") # the up arrow key 
playGround.onkey(k2, "Left") # the left arrow key 
playGround.onkey(k3, "Right") # you get it! 
playGround.onkey(k4, "Down") 
playGround.onkey(quitThis,'q') 
playGround.listen() 

我想要做的紅龜追逐藍色的龜,但它無法正常工作。任何幫助將非常感激!

+0

不能說出爲什麼downvote這個問題。 – Kevman

+0

你有什麼嘗試?爲什麼它不起作用? – tburrows13

回答

1

你失蹤的是計算機控制的藍色運動/跟隨烏龜。我們可以通過添加一個ontimer()事件處理程序來調用setheading()以保持藍色/後面是紅色/運行。再加上一點藍色/後跟的前進動作。事情是這樣的:通過改變在其forward()語句將量

from turtle import Turtle, Screen 

playGround = Screen() 
playGround.screensize(500, 500) 
playGround.title("Turtle Keys") 

run = Turtle("turtle") 
run.speed("fastest") 
run.color("blue") 
run.penup() 
run.setposition(250, 250) 

follow = Turtle("turtle") 
follow.speed("fastest") 
follow.color("red") 
follow.penup() 
follow.setposition(-250, -250) 

def k1(): 
    run.forward(10) 

def k2(): 
    run.left(45) 

def k3(): 
    run.right(45) 

def k4(): 
    run.backward(10) 

def quitThis(): 
    playGround.bye() 

def follow_runner(): 
    follow.setheading(follow.towards(run)) 
    follow.forward(1) 
    playGround.ontimer(follow_runner, 10) 

playGround.onkey(k1, "Up") # the up arrow key 
playGround.onkey(k2, "Left") # the left arrow key 
playGround.onkey(k3, "Right") # you get it! 
playGround.onkey(k4, "Down") 
playGround.onkey(quitThis, 'q') 

playGround.listen() 

follow_runner() 

playGround.mainloop() 

你可以調整藍色的性能/跟進。一旦你達到1以上,你會驚訝它趕上紅/跑。

您需要添加代碼來檢測海龜碰撞時的相關情況。