如何在龟图形中将几个按键绑定在一起?

时间:2017-12-19 03:27:28

标签: python python-3.x turtle-graphics

我正在尝试制作一个连接点的python游戏。我希望游戏注册2个按钮。示例:如果用户按下向上和向右箭头键,则乌龟向东北方向移动45度。

这是我的代码:

import turtle

flynn=turtle.Turtle()
win=turtle.Screen()
win.bgcolor("LightBlue")
flynn.pensize(7)
flynn.pencolor("lightBlue")

win.listen()

def Up():
    flynn.setheading(90)
    flynn.forward(25)

def Down():
    flynn.setheading(270)
    flynn.forward(20)

def Left():
    flynn.setheading(180)
    flynn.forward(20)

def Right():
    flynn.setheading(0)
    flynn.forward(20)

def upright():
    flynn.setheading(45)
    flynn.forward(20)

win.onkey(Up, "Up")
win.onkey(Down,"Down")
win.onkey(Left,"Left")
win.onkey(Right,"Right")

1 个答案:

答案 0 :(得分:1)

我怀疑你可以在onkeypress()onkeyrelease()事件之间干净地解决这个协调变量。 (虽然我很高兴以其他方式显示。)我提供了另一种方法,按键按下只需发送移动请求,定时器应用这些请求,无论是个人还是双倍:

from turtle import Turtle, Screen

win = Screen()

flynn = Turtle('turtle')

def process_events():
    events = tuple(sorted(key_events))

    if events and events in key_event_handlers:
        (key_event_handlers[events])()

    key_events.clear()

    win.ontimer(process_events, 200)

def Up():
    key_events.add('UP')

def Down():
    key_events.add('DOWN')

def Left():
    key_events.add('LEFT')

def Right():
    key_events.add('RIGHT')

def move_up():
    flynn.setheading(90)
    flynn.forward(25)

def move_down():
    flynn.setheading(270)
    flynn.forward(20)

def move_left():
    flynn.setheading(180)
    flynn.forward(20)

def move_right():
    flynn.setheading(0)
    flynn.forward(20)

def move_up_right():
    flynn.setheading(45)
    flynn.forward(20)

def move_down_right():
    flynn.setheading(-45)
    flynn.forward(20)

def move_up_left():
    flynn.setheading(135)
    flynn.forward(20)

def move_down_left():
    flynn.setheading(225)
    flynn.forward(20)

key_event_handlers = { \
    ('UP',): move_up, \
    ('DOWN',): move_down, \
    ('LEFT',): move_left, \
    ('RIGHT',): move_right, \
    ('RIGHT', 'UP'): move_up_right, \
    ('DOWN', 'RIGHT'): move_down_right, \
    ('LEFT', 'UP'): move_up_left, \
    ('DOWN', 'LEFT'): move_down_left, \
}

key_events = set()

win.onkey(Up, "Up")
win.onkey(Down, "Down")
win.onkey(Left, "Left")
win.onkey(Right, "Right")

win.listen()

process_events()

win.mainloop()

enter image description here

这可能会根据您的特定需求进行一些微调。 (例如,你如何处理key_events中的两个以上的事件。)