Created
February 7, 2021 16:09
-
-
Save jfurcean/15d7b88ed77a9f2c98005d72ceb3a799 to your computer and use it in GitHub Desktop.
space invaders nunchuk controls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import board | |
import digitalio | |
import analogio | |
import audioio | |
import audiocore | |
from wiichuck.nunchuk import Nunchuk | |
B_X = 0x01 | |
B_O = 0x02 | |
B_START = 0x04 | |
B_SELECT = 0x08 | |
B_DOWN = 0x10 | |
B_LEFT = 0x20 | |
B_RIGHT = 0x40 | |
B_UP = 0x80 | |
class Buttons: | |
def __init__(self): | |
self._controller = Nunchuk(board.I2C()) | |
def get_pressed(self): | |
pressed = 0x00 | |
joystick, buttons, _ = self._controller.values | |
middle = 128 | |
x = joystick.x | |
if x < middle: | |
pressed |= B_LEFT | |
elif x > middle: | |
pressed |= B_RIGHT | |
y = joystick.y | |
if y < middle: | |
pressed |= B_UP | |
elif y > middle: | |
pressed |= B_DOWN | |
if buttons.C: | |
pressed |= B_X | |
if buttons.Z: | |
pressed |= B_O | |
return pressed | |
class Audio: | |
last_audio = None | |
def __init__(self, speaker_pin, mute_pin=None): | |
self.muted = True | |
self.buffer = bytearray(128) | |
if mute_pin: | |
self.mute_pin = digitalio.DigitalInOut(mute_pin) | |
self.mute_pin.switch_to_output(value=not self.muted) | |
else: | |
self.mute_pin = None | |
self.audio = audioio.AudioOut(speaker_pin) | |
def play(self, audio_file, loop=False): | |
if self.muted: | |
return | |
self.stop() | |
wave = audiocore.WaveFile(audio_file, self.buffer) | |
self.audio.play(wave, loop=loop) | |
def stop(self): | |
self.audio.stop() | |
def mute(self, value=True): | |
self.muted = value | |
if self.mute_pin: | |
self.mute_pin.value = not value | |
buttons = Buttons() | |
audio = Audio(board.SPEAKER, board.SPEAKER_ENABLE) | |
display = board.DISPLAY |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment