Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontroller_example.py
More file actions
Latest commit
executable file
·192 lines (163 loc) · 7.05 KB
/
Copy pathcontroller_example.py
File metadata and controls
executable file
·192 lines (163 loc) · 7.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
pymlgame - controller example
=============================
This example shows how you can use your notebooks keyboard to connect to a pymlgame instance.
"""
importsys
importtime
importsocket
importlogging
logging.basicConfig(format='%(asctime)s | %(levelname)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
fromdatetimeimportdatetime
fromthreadingimportThread
importpygame
DEBUG=True
# define some constants
E_UID=pygame.USEREVENT+1
E_DOWNLOAD=pygame.USEREVENT+2
E_PLAY=pygame.USEREVENT+3
E_RUMBLE=pygame.USEREVENT+4
classReceiverThread(Thread):
"""
This thread will listen on a UDP port for packets from the game.
"""
def__init__(self, host='0.0.0.0', port=1338):
"""
Creates the socket and binds it to the given host and port.
"""
super(ReceiverThread, self).__init__()
self.host=host
self.port=port
self.sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind((self.host, self.port))
defrun(self):
whileTrue:
data, addr=self.sock.recvfrom(1024)
data=data.decode('utf-8')
logging.info('example info')
logging.warning('example warning')
logging.error('example error')
logging.critical('example critical')
ifdata.startswith('/uid/'):
e=pygame.event.Event(E_UID, {'uid': data[5:]})
pygame.event.post(e)
ifDEBUG: logging.info('uid received: {}'.format(data[5:]))
elifdata.startswith('/download/'):
e=pygame.event.Event(E_DOWNLOAD, {'url': str(data[10:])})
pygame.event.post(e)
ifDEBUG: logging.info('download of {} triggered'.format(data[10:]))
elifdata.startswith('/play/'):
e=pygame.event.Event(E_PLAY, {'filename': str(data[6:])})
pygame.event.post(e)
ifDEBUG: logging.info('playback of {} triggered'.format(data[6:]))
elifdata.startswith('/rumble/'):
e=pygame.event.Event(E_RUMBLE, {'duration': int(data[8:])})
pygame.event.post(e)
ifDEBUG: logging.info('request rumble for {}ms'.format(data[8:]))
classController(object):
def__init__(self, game_host='127.0.0.1', game_port=1338, host='0.0.0.0', port=1338):
self.game_host=game_host# Host of Mate Light
self.game_port=game_port# Port of Mate Light
self.host=host# Host of ReceiverThread
self.port=port# Port of ReceiverThread
self.sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
pygame.init()
self.screen=pygame.display.set_mode((128, 113), pygame.DOUBLEBUF, 32)
bg=pygame.image.load('kbd.png')
self.screen.blit(bg, pygame.rect.Rect(0, 0, 128, 113))
pygame.display.flip()
self.keys= [0for_inrange(14)]
self.mapping= {pygame.K_UP: 0, # Up
pygame.K_DOWN: 1, # Down
pygame.K_LEFT: 2, # Left
pygame.K_RIGHT: 3, # Right
pygame.K_a: 4, # A
pygame.K_w: 5, # B
pygame.K_s: 6, # X
pygame.K_d: 7, # Y
pygame.K_RETURN: 8, # Start
pygame.K_SPACE: 9, # Select
pygame.K_q: 10, # L1
pygame.K_1: 11, # L2
pygame.K_e: 12, # R1
pygame.K_3: 13} # R2
self.timeout=0# if the controller is in idle state a ping signal will be sent
self.rumble_active=False
self.uid=None
self._receiver=ReceiverThread(self.host, self.port)
self._receiver.setDaemon(True)
self._receiver.start()
defping(self):
ifself.uid:
ifDEBUG: logging.info('sending ping')
msg='/controller/{}/ping/{}'.format(self.uid, self._receiver.port)
self.sock.sendto(msg.encode('utf-8'), (self.game_host, self.game_port))
defsend_keys(self):
# alternative states creation: [1 if k else 0 for k in self.keys]
states='/controller/{}/states/{}'.format(self.uid, ''.join([str(k) forkinself.keys]))
ifDEBUG: logging.info('sending states {}'.format(''.join([str(k) forkinself.keys])))
self.sock.sendto(states.encode('utf-8'), (self.game_host, self.game_port))
self.timeout=time.time()
defsend_message(self, msg):
ifDEBUG: logging.info('sending of messages not yet implemented')
pass
defdisconnect(self):
ifDEBUG: logging.info('disconnecting from game')
msg='/controller/{}/kthxbye'.format(self.uid)
self.sock.sendto(msg.encode('utf-8'), (self.game_host, self.game_port))
defconnect(self):
ifDEBUG: logging.info('connecting to game')
msg='/controller/new/{}'.format(self.port)
self.sock.sendto(msg.encode('utf-8'), (self.game_host, self.game_port))
defrumble(self, duration):
ifDEBUG: logging.info('rumble not yet implemented')
pass
defdownload_sound(self, url):
ifDEBUG: logging.info('downloading of media files not yet implemented')
pass
defplay_sound(self, filename):
ifDEBUG: logging.info('playing media files not yet implemented')
pass
defhandle_inputs(self):
iftime.time() >self.timeout+30:
self.ping()
self.timeout=time.time()
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit(0)
elifevent.type==pygame.MOUSEBUTTONUP:
pygame.event.post(pygame.event.Event(pygame.QUIT))
elifevent.type==E_UID:
self.uid=event.uid
ifself.uidisnotNone:
ifevent.type==E_DOWNLOAD:
self.download_sound(event.url)
elifevent.type==E_PLAY:
self.play_sound(event.filename)
elifevent.type==E_RUMBLE:
self.rumble(event.duration)
elifevent.type==pygame.KEYDOWNorevent.type==pygame.KEYUP:
try:
button=self.mapping[event.key]
ifevent.type==pygame.KEYDOWN:
self.keys[button] =1
elifevent.type==pygame.KEYUP:
self.keys[button] =0
self.send_keys()
exceptKeyError:
break
else:
self.connect()
time.sleep(1)
if__name__=='__main__':
ctlr=Controller('127.0.0.1', 1338, '0.0.0.0', 1338)
try:
whileTrue:
ctlr.handle_inputs()
exceptKeyboardInterrupt:
ifctlr.uidisnotNone:
ctlr.disconnect()
pass