【发布时间】:2017-04-22 22:23:56
【问题描述】:
所以我读了这篇 SO 帖子: How to handle several keys pressed at the same time in Kivy?
我根据 Kivy 网站 (http://kivy.org/docs/tutorials/pong.html) 上的教程实现了 Pong 游戏。 我的 PongGame Widget 有以下方法:
def __init__(self):
super(PongGame, self).__init__()
self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
self._keyboard.bind(on_key_down = self._on_keyboard_down)
self._keyboard.bind(on_key_up = self._on_keyboard_up)
def _keyboard_closed (self):
self._keyboard.unbind(on_key_down=self._on_keyboard_down)
self._keyboard = None
def _on_keyboard_down (self, keyboard, keycode, text, modifiers):
print('### ----------------------------------- ###')
print('The keys', keycode, 'have been pressed down')
print('You pressed the key', keycode[1], '.', sep=' ', end='\n')
#print(' - text is %r' % text)
print(' - modifiers are %r' % modifiers)
if keycode[1] == 'w':
if self.player1.center_y + 20 < self.height-85:
self.player1.center_y += 20
elif keycode[1] == 's':
self.player1.center_y -= 20
elif keycode[1] == 'up':
self.player2.center_y += 20
elif keycode[1] == 'down':
self.player2.center_y -= 20
return True
"""
def _on_keyboard_up (self, keyboard, keycode, text, modifiers):
print('### ----------------------------------- ###')
print('The keys', keycode, 'have been released.')
print('You pressed the key', keycode[1], '.', sep=' ', end='\n')
#print(' - text is %r' % text)
print(' - modifiers are %r' % modifiers)
return True
"""
def _on_keyboard_up(self, *args):
print('up', args)
有了这个,我可以使用“w”、“s”、“up”和“down”来控制两个玩家。但是,仅执行最后按下按钮的操作。这是一个问题,因为当其他玩家想要移动他们的桨时,玩家可能会通过一直按下按钮来干扰彼此的输入。
我将如何实现,让两个玩家同时控制,这样他们就不会互相妨碍,除非键盘不能再按下任何按键(硬件限制)?
我目前想用 Kivy 开发桌面游戏,而不是智能手机,所以我想用真正的键盘来控制角色。
【问题讨论】:
标签: python kivy keyboard-events keydown