如何让多个键绑定在海龟图形中同时工作?

问题描述

我正在用 python 制作一个名为 pong 的游戏。

我可以在海龟图形中让 2 个不同的海龟同时响应键绑定吗?

代码如下:

import turtle


class paddle(turtle.Turtle):
    def __init__(self,x_cord,keybindings):
        super().__init__("square")

        self.color("white")
        self.penup()
        self.goto(x_cord,0)
        self.turtlesize(stretch_wid=5,stretch_len=1,outline=1)
        self.screen = turtle.Screen()
        self.screen.bgcolor("black")
        self.screen.tracer(0)
        self.screen.listen()
        self.screen.update()

        def up():
            self.goto(self.xcor(),self.ycor() + 10)
            self.screen.update()

        def down():
            self.goto(self.xcor(),self.ycor() - 10)
            self.screen.update()

        self.screen.onkey(up,keybindings[0])
        self.screen.onkey(down,keybindings[1])


paddle_1 = paddle(-350,["Up","Down"])
paddle_2 = paddle(350,["w","s"])

food.screen.exitonclick()

解决方法

这曾经是我纠结了很长时间的一个问题,得出的结论是不可能(请证明我是错的,因为我对解决方案感兴趣).

我分析了 this 很好的答案,它解释了如何绑定两个箭头键以进行对角线移动,但它一次只能执行一步,就像您的代码允许海龟同时移动一样长就像让他们一步一步地移动。

无论如何,这种情况促使我进一步接受了多功能的 Pygame python 包。