我正在尝试制作一个连接点的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")
答案 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()
这可能会根据您的特定需求进行一些微调。 (例如,你如何处理key_events
中的两个以上的事件。)