gpt4 book ai didi

python - 如何在 turtle 图形中将多个按键绑定(bind)在一起?

转载 作者:太空宇宙 更新时间:2023-11-04 04:52:31 25 4
gpt4 key购买 nike

我正在尝试制作一个点连线 python 游戏。我想让游戏注册 2 次按钮按下。示例:如果用户按向上和向右箭头键, turtle 将向东北方向移动 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")

最佳答案

我怀疑您能否干净地解决 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 中处理两个以上的事件)。

关于python - 如何在 turtle 图形中将多个按键绑定(bind)在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com