In order to play with other to a blind test music game, I created a small pygame script that plays a song and wait for the player to press a button, wait for its response and display the artist/title of the song. It was my first experiment in game programming and pygame made it very easy.
To make it more fun, I decided to use my wiimotes as input devices. Gathering information from the GNU/Linux Port for the Wii and a script from Cadex found on the web I created this piece of code to send wiimote events to pygame.
class Wiimote(object):
wii_buttons = {'A1300008': 'A', 'A1300004': 'B'}
def __init__(self, address, event):
self.event = event
self.address = address
self.status = "Disconnected"
self.receivesocket = bluetooth.BluetoothSocket(bluetooth.L2CAP)
self.controlsocket = bluetooth.BluetoothSocket(bluetooth.L2CAP)
self.connect()
def connect(self):
self.receivesocket.connect((self.address, 0x13))
self.controlsocket.connect((self.address, 0x11))
if self.receivesocket and self.controlsocket:
if self.event == WIIMOTE1:
data = "521110"
else:
data = "521120"
self.controlsocket.send(data.decode('hex'))
self.status = "Connected"
thread.start_new_thread(self.receive, ())
def receive(self):
self.receivesocket.settimeout(0.1)
while self.status == "Connected":
try:
data = self.receivesocket.recv(23).encode('hex').upper()
if data in self.wii_buttons:
event = pygame.event.Event(self.event,
button=self.wii_buttons[data])
pygame.event.post(event)
except bluetooth.BluetoothError:
pass
self.receivesocket.close()
self.controlsocket.close()
self.status = "Disconnected"
What this class does is creating two sockets to communicate with the wiimote located at address. Once the connection is established, we send a simple command to light the led on the joypad and we create a thread that will receive all the data and post the events comming from the pad to the pygame event loop.