Python键盘多个海龟对象

2024-04-27 04:19:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个程序,在这个程序中海龟对象响应按键。我能做到这一点,但我似乎不明白如何移动第二个乌龟物体,它是由计算机控制的,而第一个是移动的。任何帮助都将不胜感激。在

这是我的代码:

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

Tags: 对象fromimport程序defrooth2h1
2条回答

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

I can't seem to understand how to move a second Turtle object, which is controlled by the computer, while the first one is moving.

下面是一些最小的代码,如您所描述的那样。绿海龟Pokey由计算机控制,而红色turtle 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的处理程序应该在运行时锁定其他事件,等等),但应该给你一个基本的想法,如何去做。在

相关问题 更多 >