我正在创建一个游戏,用户使用键盘移动乌龟以避免另一只乌龟。这是我的代码:
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 :(得分:1)
你所缺少的是蓝色/跟随乌龟的计算机控制运动。我们可以通过添加ontimer()
事件处理程序来执行此操作,该处理程序在setheading()
上调用towards()
以保持蓝色/跟随红色/运行。加上一点蓝色的前进动作/跟随。像这样:
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()
您可以通过更改其forward()
语句中的移动量来调整蓝色/后续的效果。一旦你超过1,你就会惊讶地发现它有多快赶上红色/跑步。
您需要添加代码以检测海龟何时发生碰撞以及随后发生的事情。