Python - 键盘多个海龟对象

0 投票
2 回答
1494 浏览
提问于 2025-04-17 21:32

我想创建一个程序,让一个乌龟对象可以对按键做出反应。我能做到这一点,但我不太明白如何在第一个乌龟移动的同时,让第二个乌龟对象(由计算机控制)也能移动。希望能得到一些帮助。

这是我的代码:

from turtle import *
from Tkinter import Tk
root = Tk()
root.withdraw()
turtle = Turtle()
def h1():turtle.forward(10)
def h2():turtle.left(45)
def h3():turtle.right(45)
def h4():turtle.back(10)
def h5(root=root):root.quit()
onkey(h1,"Up")
onkey(h2,"Left")
onkey(h3,"Right")
onkey(h4,"Down")
onkey(h5,"q")
listen()
root.mainloop()

2 个回答

0

我似乎不太明白怎么在第一个乌龟移动的时候,让第二个乌龟也能被电脑控制地移动。

下面是一些简单的代码,正如你所描述的那样。绿色的乌龟Pokey是由电脑控制的,而红色的乌龟Hokey是由用户控制的(先点击窗口,这样你的按键才能被识别):

from turtle import Turtle, Screen

def move_pokey():
    pokey.forward(10)
    x, y = pokey.position()

    if not (-width/2 < x < width/2 and -height/2 < y < height/2):
        pokey.undo()
        pokey.left(90)

    screen.ontimer(move_pokey, 100)

hokey = Turtle(shape="turtle")
hokey.color("red")
hokey.penup()

pokey = Turtle(shape="turtle")
pokey.setheading(30)
pokey.color("green")
pokey.penup()

screen = Screen()

width = screen.window_width()
height = screen.window_height()

screen.onkey(lambda: hokey.forward(10), "Up")
screen.onkey(lambda: hokey.left(45), "Left")
screen.onkey(lambda: hokey.right(45), "Right")
screen.onkey(lambda: hokey.back(10), "Down")
screen.onkey(screen.bye, "q")

screen.listen()

screen.ontimer(move_pokey, 100)

screen.mainloop()

这段代码还没有完成(比如定时器事件的关闭应该更干净,Hokey的处理程序在运行时应该锁定额外的事件等等),但应该能给你一个基本的思路,告诉你该怎么做。

1

listen() 之前插入一个第二只海龟,并让它能通过键盘上的 w、a、s、d 键来移动:

turtle2 = Turtle()
def h11():turtle2.forward(10)
def h21():turtle2.left(45)
def h31():turtle2.right(45)
def h41():turtle2.back(10)
onkey(h11,"w")
onkey(h21,"a")
onkey(h31,"d")
onkey(h41,"s")

撰写回答