Skip to content

Instantly share code, notes, and snippets.

@son-link
Created January 18, 2025 10:39
Show Gist options
  • Select an option

  • Save son-link/01f690888637f649ab62a93524e62fdf to your computer and use it in GitHub Desktop.

Select an option

Save son-link/01f690888637f649ab62a93524e62fdf to your computer and use it in GitHub Desktop.
def getBtnPressed():
"""Detects which button or key is pressed and returns a text string representing what was pressed
Returns:
str: A text string representing what was pressed
"""
if (
pyxel.btnp(pyxel.GAMEPAD1_BUTTON_DPAD_UP) or
pyxel.btnp(pyxel.KEY_UP)
):
return 'up'
elif (
pyxel.btnp(pyxel.GAMEPAD1_BUTTON_DPAD_DOWN) or
pyxel.btnp(pyxel.KEY_DOWN)
):
return 'down'
elif (
pyxel.btnp(pyxel.GAMEPAD1_BUTTON_DPAD_LEFT) or
pyxel.btnp(pyxel.KEY_LEFT)
):
return 'left'
elif (
pyxel.btnp(pyxel.GAMEPAD1_BUTTON_DPAD_RIGHT) or
pyxel.btnp(pyxel.KEY_RIGHT)
):
return 'right'
elif (
pyxel.btnp(pyxel.GAMEPAD1_BUTTON_A) or
pyxel.btnp(pyxel.KEY_Z)
):
return 'a'
elif (
pyxel.btnp(pyxel.GAMEPAD1_BUTTON_B) or
pyxel.btnp(pyxel.KEY_X)
):
return 'b'
elif (
pyxel.btnp(pyxel.GAMEPAD1_BUTTON_START) or
pyxel.btnp(pyxel.KEY_RETURN)
):
return 'start'
elif (
pyxel.btnp(pyxel.GAMEPAD1_BUTTON_BACK) or
pyxel.btnp(pyxel.KEY_SPACE)
):
return 'select'

getBtnPressed is a function to use in Pyxel, which returns a string depending on the key or button pressed, thus avoiding having to use long IF statements to know if, for example, the up arrow key was pressed or that same direction on the d-pad of a controller.

Copy the function anywhere in your game code. Remember to add self as a function parameter if you will include it in a class.

The values returned are:

  • Arrow up or press up on the d-pad: 'up'.
  • Arrow down or press down on the d-pad: 'down'.
  • Left arrow or press left on the d-pad: 'left'
  • Right arrow or press right on the d-pad: 'right'
  • Z key or A button on the controller: 'a'
  • X key or B button on the joystick: 'b'
  • Enter key or Start button on the controller: 'start'
  • Space key or Select/Back button on the joystick: 'select'

This function has been tested with an Xbox controller and the RS36S controller.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment