Skip to content

Commit cc20d8f

Browse files
author
XenGi
committed
polishing and version bump
1 parent d75090b commit cc20d8f

11 files changed

+59
-52
lines changed

controller_example.py

+19-14
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
@@ -104,35 +108,41 @@ def __init__(self, game_host='127.0.0.1', game_port=1338, host='0.0.0.0', port=1
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

-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,6 @@ def __init__(self, width=40, height=16, ip='127.0.0.1', port=1337, dotsize=10):
5757
self.clock = pygame.time.Clock()
5858
self.matrix = []
5959
for c in range(self.width * self.height * 3):
60-
# fill matrix with black color
6160
self.matrix.append(0)
6261

6362
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

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

pymlgame/__init__.py

+16-12
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
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'
@@ -15,17 +19,17 @@
1519
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)

pymlgame/controller.py

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

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

77
from uuid import uuid4
@@ -11,7 +11,7 @@
1111
from queue import Queue
1212
from threading import Thread
1313

14-
from pymlgame.locals import *
14+
from pymlgame.locals import E_NEWCTLR, E_DISCONNECT, E_PING, E_KEYUP, E_KEYDOWN, E_MESSAGE, E_RUMBLE
1515
from pymlgame.event import Event
1616

1717

@@ -39,7 +39,7 @@ def _new_controller(self, addr, port):
3939
for uid, controller in self.controllers.items():
4040
if controller[0] == addr:
4141
# duplicate address. sending the uid again
42-
print('/uid/{} => {}:{}'.format(uid, addr, port))
42+
#print('/uid/{} => {}:{}'.format(uid, addr, port))
4343
self.sock.sendto('/uid/{}'.format(uid).encode('utf-8'), (addr, port))
4444
return False
4545

@@ -48,7 +48,7 @@ def _new_controller(self, addr, port):
4848
self.controllers[uid] = [addr, port, '00000000000000', time.time()]
4949

5050
# tell the controller about it
51-
print('/uid/{} => {}:{}'.format(uid, addr, port))
51+
#print('/uid/{} => {}:{}'.format(uid, addr, port))
5252
self.sock.sendto('/uid/{}'.format(uid).encode('utf-8'), (addr, port))
5353

5454
# create event for pymlgame
@@ -128,10 +128,10 @@ def send(self, uid, event, payload):
128128
addr = self.controllers[uid][0]
129129
port = self.controllers[uid][1]
130130
if event == E_MESSAGE:
131-
print('/message/{} => {}:{}'.format(payload, addr, port))
131+
#print('/message/{} => {}:{}'.format(payload, addr, port))
132132
return sock.sendto('/message/{}'.format(payload).encode('utf-8'), (addr, port))
133133
elif event == E_RUMBLE:
134-
print('/rumble/{} => {}:{}'.format(payload, addr, port))
134+
#print('/rumble/{} => {}:{}'.format(payload, addr, port))
135135
return sock.sendto('/rumble/{}'.format(payload).encode('utf-8'), (addr, port))
136136
else:
137137
pass
@@ -147,7 +147,6 @@ def run(self):
147147
data, sender = self.sock.recvfrom(1024)
148148
addr = sender[0]
149149
msg = data.decode('utf-8')
150-
print('New msg: ' + msg)
151150
if msg.startswith('/controller/'):
152151
try:
153152
uid = msg.split('/')[2]

pymlgame/event.py

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

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

77
from pymlgame.locals import E_KEYDOWN, E_KEYUP

pymlgame/locals.py

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

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

77
# event types
@@ -52,4 +52,4 @@
5252
GREY3 = (178, 178, 178)
5353
GREY2 = (204, 204, 204)
5454
GREY1 = (229, 229, 229)
55-
WHITE = (255, 255, 255)
55+
WHITE = (255, 255, 255)

pymlgame/screen.py

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

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

77
import socket
88

9-
from pymlgame.locals import *
9+
from pymlgame.locals import BLACK
1010
from pymlgame.surface import Surface
1111

1212

pymlgame/surface.py

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

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

77
import math
88

9-
from pymlgame.locals import *
9+
from pymlgame.locals import BLACK
1010

1111

1212
class Surface(object):
@@ -111,4 +111,4 @@ def replace_color(self, before, after):
111111
for x in range(self.width):
112112
for y in range(self.height):
113113
if self.matrix[x][y] == before:
114-
self.matrix[x][y] = after
114+
self.matrix[x][y] = after

setup.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
__copyright__ = 'Copyright 2014, Ricardo Band'
1010
__credits__ = ['Ricardo Band']
1111
__license__ = 'MIT'
12-
__version__ = '0.2.0'
12+
__version__ = '0.3.0'
1313
__maintainer__ = 'Ricardo Band'
1414
__email__ = '[email protected]'
1515
__status__ = 'Development'
@@ -25,16 +25,16 @@
2525
def read(fname):
2626
return open(os.path.join(os.path.dirname(__file__), fname)).read()
2727

28-
setup(name='pymlgame',
28+
setup(name='PyMLGame',
2929
version=__version__,
3030
author=__author__,
3131
author_email=__email__,
3232
maintainer=__maintainer__,
3333
maintainer_email=__email__,
34-
url='http://github.com/c-base/pymlgame',
35-
description='pymlgame is an abstraction layer to easily build games for Mate Light inspired by pygame.',
34+
url='http://github.com/PyMLGame/pymlgame',
35+
description='PyMLGame is an abstraction layer to easily build games for Mate Light inspired by PyGame.',
3636
long_description=read('README.md'),
37-
download_url='https://github.com/c-base/pymlgame/archive/master.zip',
37+
download_url='https://github.com/PyMLGame/pymlgame/archive/master.zip',
3838
classifiers=['Development Status :: 4 - Beta',
3939
'Environment :: Console',
4040
'Intended Audience :: Developers',

0 commit comments

Comments
 (0)