問題描述
所以,不久前,我開始自學(xué) kivy.我從主要的 kivy 網(wǎng)站開始,瀏覽了它的 pong 制作教程,完成后我決定嘗試給它關(guān)鍵輸入.我似乎找不到任何關(guān)于 kivy 鍵輸入的指南!任何人都知道某種教程或可以提供一些易于理解的代碼?我確實(shí)在 kivy 的示例文件夾中查看了鍵盤偵聽器,但如果我應(yīng)該使用它,我不太確定如何使用它.
So, awhile ago, I started teaching myself kivy. I started with the main kivy website and went through its pong making tutorial and upon finishing that I decided to try and give it key input. I just can't seem to find any kind of guide to key input with kivy! Anyone know some kind of tutorial or can provide some easy to understand code? I did look at the Keyboard Listener in the examples folder of kivy, but I'm not quite sure how to use that if I'm supposed to.
感謝您的幫助.
推薦答案
我猜你在問如何用鍵盤控制槳.我假設(shè)您的計(jì)算機(jī)上運(yùn)行了最終的乒乓球代碼(如果沒有,您可以在 本節(jié)).
I guess you are asking how to control the paddles with the keyboard. I assume you have the final ping pong codes running on your computer (If not, you can find them at the end of this section).
1 - 在 main.py
中導(dǎo)入 Window 類:
1 - In the main.py
import the Window class:
from kivy.core.window import Window
2 - 重新定義 PongGame
類的開頭,使其如下所示:
2 - Redefine the beginning of the PongGame
class so it looks like the following:
class PongGame(Widget):
ball = ObjectProperty(None)
player1 = ObjectProperty(None)
player2 = ObjectProperty(None)
def __init__(self, **kwargs):
super(PongGame, self).__init__(**kwargs)
self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
self._keyboard.bind(on_key_down=self._on_keyboard_down)
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):
if keycode[1] == 'w':
self.player1.center_y += 10
elif keycode[1] == 's':
self.player1.center_y -= 10
elif keycode[1] == 'up':
self.player2.center_y += 10
elif keycode[1] == 'down':
self.player2.center_y -= 10
return True
瞧!按 w
和 s
為左槳,按 up
和 down
為右槳.
Voilà! Press w
and s
for the left paddle and up
and down
for the right paddle.
這篇關(guān)于您如何使用 kivy 檢查鍵盤事件?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!