让一只Python龟追逐另一只乌龟

Make one Python turtle chase another turtle

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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()

我想让红乌龟追蓝乌龟,但它不起作用。任何帮助都将不胜感激!


你所缺少的是电脑控制的蓝海龟的动作。我们可以通过添加一个在towards()上调用setheading()ontimer()事件处理程序来做到这一点,以保持蓝色/跟随红色/运行。再加上一点蓝色/跟车的前进动作。像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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()语句中的移动量来调整blue/follow的性能。一旦你超过1,你会惊讶于它是如何迅速赶上红色/奔跑。

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