0

我正在创建一个游戏,用户使用键盘移动乌龟以避免另一只乌龟。这是我的代码:

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()

我想让红海龟追逐蓝海龟,但它不起作用。

4

1 回答 1

2

您缺少的是蓝色/跟随海龟的计算机控制运动。我们可以通过添加一个ontimer()事件处理程序来做到这一点,该处理程序调用setheading()ontowards()以保持蓝色/跟随面向红色/运行。再加上蓝色/跟随的一点向前运动。像这样的东西:

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,您会惊讶于它以多快的速度赶上 red/run。

您需要添加代码来检测海龟何时发生碰撞以及随后发生的任何事情。

于 2017-04-16T23:02:54.033 回答