Skip to content

Commit 45d83e2

Browse files
author
XenGi
committed
Merge branch 'release/v0.3.0'
2 parents 1cc0b95 + cc20d8f commit 45d83e2

12 files changed

+94
-83
lines changed

controller_example.py

+20-15
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python2.7
1+
#!/usr/bin/env python2
22
# -*- coding: utf-8 -*-
33

44
"""
@@ -18,6 +18,8 @@
1818

1919
import pygame
2020

21+
DEBUG = True
22+
2123
# define some constants
2224
E_UID = pygame.USEREVENT + 1
2325
E_DOWNLOAD = pygame.USEREVENT + 2
@@ -29,7 +31,7 @@ class ReceiverThread(Thread):
2931
"""
3032
This thread will listen on a UDP port for packets from the game.
3133
"""
32-
def __init__(self, host='0.0.0.0', port=11337):
34+
def __init__(self, host='0.0.0.0', port=1338):
3335
"""
3436
Creates the socket and binds it to the given host and port.
3537
"""
@@ -48,24 +50,26 @@ def run(self):
4850
logging.warning('example warning')
4951
logging.error('example error')
5052
logging.critical('example critical')
51-
#print(datetime.now(), '<<< {}'.format(data))
5253
if data.startswith('/uid/'):
53-
#print(datetime.now(), '### uid', data[5:], 'received')
5454
e = pygame.event.Event(E_UID, {'uid': int(data[5:])})
5555
pygame.event.post(e)
56+
if DEBUG: logging.info('uid received: {}'.format(data[5:]))
5657
elif data.startswith('/download/'):
5758
e = pygame.event.Event(E_DOWNLOAD, {'url': str(data[10:])})
5859
pygame.event.post(e)
60+
if DEBUG: logging.info('download of {} triggered'.format(data[10:]))
5961
elif data.startswith('/play/'):
6062
e = pygame.event.Event(E_PLAY, {'filename': str(data[6:])})
6163
pygame.event.post(e)
64+
if DEBUG: logging.info('playback of {} triggered'.format(data[6:]))
6265
elif data.startswith('/rumble/'):
63-
e = pygame.event.Event(E_RUMBLE, {'duration': float(data[8:].replace(',', '.'))})
66+
e = pygame.event.Event(E_RUMBLE, {'duration': int(data[8:])})
6467
pygame.event.post(e)
68+
if DEBUG: logging.info('request rumble for {}ms'.format(data[8:]))
6569

6670

6771
class Controller(object):
68-
def __init__(self, game_host='127.0.0.1', game_port=1338, host='0.0.0.0', port=11337):
72+
def __init__(self, game_host='127.0.0.1', game_port=1338, host='0.0.0.0', port=1338):
6973
self.game_host = game_host # Host of Mate Light
7074
self.game_port = game_port # Port of Mate Light
7175
self.host = host # Host of ReceiverThread
@@ -98,41 +102,47 @@ def __init__(self, game_host='127.0.0.1', game_port=1338, host='0.0.0.0', port=1
98102
self.rumble_active = False
99103
self.uid = None
100104

101-
self._receiver = ReceiverThread(host, port)
105+
self._receiver = ReceiverThread(self.host, self.port)
102106
self._receiver.setDaemon(True)
103107
self._receiver.start()
104108

105109
def ping(self):
106110
if self.uid:
111+
if DEBUG: logging.info('sending ping')
107112
msg = '/controller/{}/ping/{}'.format(self.uid, self._receiver.port)
108113
self.sock.sendto(msg.encode('utf-8'), (self.game_host, self.game_port))
109-
#print(datetime.now(), '>>>', msg)
110114

111115
def send_keys(self):
112116
# alternative states creation: [1 if k else 0 for k in self.keys]
113117
states = '/controller/{}/states/{}'.format(self.uid, ''.join([str(k) for k in self.keys]))
118+
if DEBUG: logging.info('sending states {}'.format(''.join([str(k) for k in self.keys])))
114119
self.sock.sendto(states.encode('utf-8'), (self.game_host, self.game_port))
115-
#print(datetime.now(), '>>>' + states)
116120
self.timeout = time.time()
117121

118122
def send_message(self, msg):
123+
if DEBUG: logging.info('sending of messages not yet implemented')
119124
pass
120125

121126
def disconnect(self):
127+
if DEBUG: logging.info('disconnecting from game')
122128
msg = '/controller/{}/kthxbye'.format(self.uid)
123129
self.sock.sendto(msg.encode('utf-8'), (self.game_host, self.game_port))
124130

125131
def connect(self):
132+
if DEBUG: logging.info('connecting to game')
126133
msg = '/controller/new/{}'.format(self.port)
127134
self.sock.sendto(msg.encode('utf-8'), (self.game_host, self.game_port))
128135

129136
def rumble(self, duration):
137+
if DEBUG: logging.info('rumble not yet implemented')
130138
pass
131139

132140
def download_sound(self, url):
141+
if DEBUG: logging.info('downloading of media files not yet implemented')
133142
pass
134143

135144
def play_sound(self, filename):
145+
if DEBUG: logging.info('playing media files not yet implemented')
136146
pass
137147

138148
def handle_inputs(self):
@@ -147,11 +157,9 @@ def handle_inputs(self):
147157
elif event.type == pygame.MOUSEBUTTONUP:
148158
pygame.event.post(pygame.event.Event(pygame.QUIT))
149159
elif event.type == E_UID:
150-
#print(datetime.now(), '### UID event received', event.uid)
151160
self.uid = event.uid
152161

153162
if self.uid is not None:
154-
#print(datetime.now(), '### UID set. checking other events')
155163
if event.type == E_DOWNLOAD:
156164
self.download_sound(event.url)
157165
elif event.type == E_PLAY:
@@ -162,22 +170,19 @@ def handle_inputs(self):
162170
try:
163171
button = self.mapping[event.key]
164172
if event.type == pygame.KEYDOWN:
165-
#print('{} | {}'.format(event.key, button))
166173
self.keys[button] = 1
167174
elif event.type == pygame.KEYUP:
168-
#print('{} | {}'.format(event.key, button))
169175
self.keys[button] = 0
170176
self.send_keys()
171177
except KeyError:
172178
break
173179
else:
174-
#print(datetime.now(), '### UID not set. connecting to game.')
175180
self.connect()
176181
time.sleep(1)
177182

178183

179184
if __name__ == '__main__':
180-
ctlr = Controller('127.0.0.1', 1338, '0.0.0.0', 11337)
185+
ctlr = Controller('127.0.0.1', 1338, '0.0.0.0', 1338)
181186
try:
182187
while True:
183188
ctlr.handle_inputs()

emulator.py

+23-8
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python2.7
1+
#!/usr/bin/env python2
22
# -*- coding: utf-8 -*-
33

44
"""
@@ -7,13 +7,27 @@
77
88
This little program emulates the awesome Mate Light, just in case you're not on c-base space station but want to send
99
something to it.
10+
11+
Usage:
12+
emulator.py [-w=<px>] [-h=<px>] [--host=<ip>] [--port=<num>] [--dot=<size>]
13+
emulator.py --help
14+
emulator.py --version
15+
16+
Options:
17+
--help Show this screen.
18+
--version Show version.
19+
-w=<px> Width in pixels [default: 40].
20+
-h=<px> Height in pixels [default: 16].
21+
--host=<host> Bind to IP address [default: 127.0.0.1].
22+
--port=<port> Bind to Port [default: 1337].
23+
--dot=<px> Size of dots in pixels [default: 10].
1024
"""
1125

1226
__author__ = 'Ricardo Band'
1327
__copyright__ = 'Copyright 2014, Ricardo Band'
1428
__credits__ = ['Ricardo Band']
1529
__license__ = 'MIT'
16-
__version__ = '0.2.0'
30+
__version__ = '0.3.0'
1731
__maintainer__ = 'Ricardo Band'
1832
__email__ = '[email protected]'
1933
__status__ = 'Development'
@@ -22,27 +36,27 @@
2236
import socket
2337

2438
import pygame
39+
from docopt import docopt
2540

2641

2742
class Emu(object):
2843
"""
2944
The Emulator is a simple pygame game.
3045
"""
31-
def __init__(self, width=40, height=16, ip='127.0.0.1', port=1337):
46+
def __init__(self, width=40, height=16, ip='127.0.0.1', port=1337, dotsize=10):
3247
"""
3348
Creates a screen with the given size, generates the matrix for the Mate bottles and binds the socket for
3449
incoming frames.
3550
"""
3651
self.width = width
3752
self.height = height
53+
self.dotsize = dotsize
3854
pygame.init()
39-
# one mate bottle is 10x10px
40-
self.screen = pygame.display.set_mode([self.width * 10, self.height * 10])
55+
self.screen = pygame.display.set_mode([self.width * self.dotsize, self.height * self.dotsize])
4156
pygame.display.set_caption("Mate Light Emu")
4257
self.clock = pygame.time.Clock()
4358
self.matrix = []
4459
for c in range(self.width * self.height * 3):
45-
# fill matrix with black color
4660
self.matrix.append(0)
4761

4862
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
@@ -71,7 +85,7 @@ def update(self):
7185
if pixel < pixels:
7286
pygame.draw.circle(self.screen,
7387
(self.matrix[pixel], self.matrix[pixel + 1], self.matrix[pixel + 2]),
74-
(x * 10 + 5, y * 10 + 5), 5, 0)
88+
(x * self.dotsize + self.dotsize / 2, y * self.dotsize + self.dotsize / 2), self.dotsize / 2, 0)
7589

7690
def render(self):
7791
"""
@@ -101,5 +115,6 @@ def gameloop(self):
101115

102116

103117
if __name__ == '__main__':
104-
EMU = Emu(40, 16, '127.0.0.1', 1337)
118+
ARGS = docopt(__doc__, version=__version__)
119+
EMU = Emu(int(ARGS['-w']), int(ARGS['-h']), ARGS['--host'], int(ARGS['--port']), int(ARGS['--dot']))
105120
EMU.gameloop()

game_example.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,15 @@
1313
__copyright__ = 'Copyright 2014, Ricardo Band'
1414
__credits__ = ['Ricardo Band']
1515
__license__ = 'MIT'
16-
__version__ = '0.2.0'
16+
__version__ = '0.3.0'
1717
__maintainer__ = 'Ricardo Band'
1818
__email__ = '[email protected]'
1919
__status__ = 'Development'
2020

2121
from datetime import datetime
2222

2323
import pymlgame
24-
from pymlgame.locals import *
24+
from pymlgame.locals import WHITE, BLUE, GREEN, CYAN, MAGENTA, YELLOW, RED, BLACK, E_NEWCTLR, E_DISCONNECT, E_KEYDOWN, E_KEYUP, E_PING
2525
from pymlgame.screen import Screen
2626
from pymlgame.clock import Clock
2727
from pymlgame.surface import Surface

icons_android.xcf

37.9 KB
Binary file not shown.

pymlgame/__init__.py

+20-16
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,35 @@
11
# -*- coding: utf-8 -*-
22

3+
"""
4+
PyMLGame
5+
"""
6+
37
__author__ = 'Ricardo Band'
48
__copyright__ = 'Copyright 2014, Ricardo Band'
59
__credits__ = ['Ricardo Band']
610
__license__ = 'MIT'
7-
__version__ = '0.2.0'
11+
__version__ = '0.3.0'
812
__maintainer__ = 'Ricardo Band'
913
__email__ = '[email protected]'
1014
__status__ = 'Development'
1115

12-
# from pymlgame.locals import *
13-
# from pymlgame.screen import Screen
14-
# from pymlgame.clock import Clock
15-
# from pymlgame.surface import Surface
16+
from pymlgame.locals import *
17+
from pymlgame.screen import Screen
18+
from pymlgame.clock import Clock
19+
from pymlgame.surface import Surface
1620
from pymlgame.controller import Controller
1721

18-
_ctlr = Controller()
22+
CONTROLLER = Controller()
1923

2024

2125
def init(host='0.0.0.0', port=1338):
2226
"""
23-
Initialize pymlgame. This creates a controller thread that listens for game controllers and events.
27+
Initialize PyMLGame. This creates a controller thread that listens for game controllers and events.
2428
"""
25-
_ctlr.host = host
26-
_ctlr.port = port
27-
_ctlr.setDaemon(True) # because it's a deamon it will exit together with the main thread
28-
_ctlr.start()
29+
CONTROLLER.host = host
30+
CONTROLLER.port = port
31+
CONTROLLER.setDaemon(True) # because it's a deamon it will exit together with the main thread
32+
CONTROLLER.start()
2933

3034

3135
def get_events(maximum=10):
@@ -35,10 +39,10 @@ def get_events(maximum=10):
3539
events = []
3640
for ev in range(0, maximum):
3741
try:
38-
if _ctlr.queue.empty():
42+
if CONTROLLER.queue.empty():
3943
break
4044
else:
41-
events.append(_ctlr.queue.get_nowait())
45+
events.append(CONTROLLER.queue.get_nowait())
4246
except NameError:
4347
not_initialized()
4448
events = False
@@ -50,11 +54,11 @@ def get_event():
5054
"""
5155
Get the next event in the queue if there is one.
5256
"""
53-
if not _ctlr.queue.empty():
54-
return _ctlr.queue.get_nowait()
57+
if not CONTROLLER.queue.empty():
58+
return CONTROLLER.queue.get_nowait()
5559
else:
5660
return False
5761

5862

5963
def not_initialized():
60-
print('pymlgame is not initialized correctly. Use pymlgame.init() first.')
64+
print('PyMLGame is not initialized correctly. Use pymlgame.init() first.')

pymlgame/clock.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# -*- coding: utf-8 -*-
22

33
"""
4-
pymlgame - Clock
4+
PyMLGame - Clock
55
"""
66

77
import time
@@ -21,5 +21,5 @@ def tick(self):
2121
"""
2222
Let the Clock tick.
2323
"""
24-
#TODO: I think this is not the correct way. Should think about this again..
25-
time.sleep(1.0/self.fps)
24+
#TODO: I think this is not the correct way. I should think about this again..
25+
time.sleep(1.0/self.fps)

0 commit comments

Comments
 (0)