Forum Archive

Hardware keyboard input when scene is running

KiloPasztetowej

Hey. I searched and searched but I couldn’t find definitive answer to the question, whether querying hardware keyboard state is possible in Pythonista when using scene. I know it can be done with UIKit but this doesn’t fit my needs. I love my iPad and I’d like to use it for some quick prototypes for my games but I just prefer keyboard input over touch.
Any support would be welcome (events or just queries for keys)!

mikael

@KiloPasztetowej, I assume that by UIKit support you are referring to the ui.View.get_key_commands and key_command(sender) methods.

Since scene always runs in a
UI view, you can create a custom ui.View that utilizes the above methods, and then use that as your scene’s view.

Something like this – end with a two-finger swipe down:

import ui
import scene


class MyKbHandler(ui.View):

    def __init__(self, my_scene, **kwargs):
        super().__init__(**kwargs)
        sceneview = scene.SceneView(
            frame=self.bounds, flex='WH',
        )
        sceneview.scene = self.scene = my_scene
        self.add_subview(sceneview)

    def get_key_commands(self):
        return [
            # Custom commands
            { 'input': 'A' }
        ]

    def key_command(self, sender):
        # Process commands, e.g.:
        if sender['input'] == 'A':
            self.scene.accelerate()


class MyScene(scene.Scene):

    def setup(self):
        self.ship = scene.SpriteNode('spc:PlayerShip1Orange')
        self.ship.position = self.size / 2
        self.add_child(self.ship)

    def accelerate(self):
        x, y = self.ship.position
        self.ship.position = (x, y + 20)


root = MyKbHandler(my_scene=MyScene())

root.present('fullscreen', hide_title_bar=True)
KiloPasztetowej

Great! Works like a charm and that’s exactly what I need. Thank you very much 🙂

salihagenter

Agenter is the best place for anyone who wants to earn more money online. Here you can make money in the form of commission by working for the business offers or referring them to the right individuals. You can also help others to make money online by referring to the leads. To know more about online earning