Skip to content

Commit 8222618

Browse files
author
XenGi
committed
code optimizations. brightness control was deprecated so it got removed.
1 parent eb7d221 commit 8222618

File tree

6 files changed

+135
-104
lines changed

6 files changed

+135
-104
lines changed

emulator.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
pymlgame - Mate Light emulator
66
==============================
77
8-
This little program emulates the awesome Mate Light, just in case you're not
9-
at c-base but want to code something for it.
8+
This little program emulates the awesome Mate Light, just in case you're not on c-base space station but want to send
9+
something to it.
1010
"""
1111

1212
__author__ = 'Ricardo Band'
@@ -28,31 +28,36 @@ class Emu(object):
2828
"""
2929
The Emulator is a simple pygame game.
3030
"""
31-
def __init__(self, width=50, height=28, ip='127.0.0.1', port=1337):
31+
def __init__(self, width=40, height=16, ip='127.0.0.1', port=1337):
3232
"""
33-
Creates a screen with the given size, generates the matrix for the
34-
Mate bottles and binds the socket for incoming frames.
33+
Creates a screen with the given size, generates the matrix for the Mate bottles and binds the socket for
34+
incoming frames.
3535
"""
3636
self.width = width
3737
self.height = height
3838
pygame.init()
39-
self.screen = pygame.display.set_mode([self.width * 10,
40-
self.height * 10])
39+
# one mate bottle is 10x10px
40+
self.screen = pygame.display.set_mode([self.width * 10, self.height * 10])
4141
pygame.display.set_caption("Mate Light Emu")
4242
self.clock = pygame.time.Clock()
4343
self.matrix = []
4444
for c in range(self.width * self.height * 3):
45+
# fill matrix with black color
4546
self.matrix.append(0)
4647

4748
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
4849
self.sock.bind((ip, port))
50+
# size is width * height * 3 (rgb) + 4 (checksum)
51+
self.packetsize = self.width * self.height * 3 + 4
4952

5053
def recv_data(self):
5154
"""
5255
Grab the next frame and put it on the matrix.
5356
"""
54-
data, addr = self.sock.recvfrom(self.width * self.height * 3 + 4)
55-
self.matrix = map(ord, data.strip())[:-4]
57+
data, addr = self.sock.recvfrom(self.packetsize)
58+
matrix = map(ord, data.strip())
59+
if len(matrix) == self.packetsize:
60+
self.matrix = matrix[:-4]
5661

5762
def update(self):
5863
"""
@@ -64,9 +69,8 @@ def update(self):
6469
pixel = y * self.width * 3 + x * 3
6570
#TODO: sometimes the matrix is not as big as it should
6671
if pixel < pixels:
67-
pygame.draw.circle(self.screen, (self.matrix[pixel],
68-
self.matrix[pixel + 1],
69-
self.matrix[pixel + 2]),
72+
pygame.draw.circle(self.screen,
73+
(self.matrix[pixel], self.matrix[pixel + 1], self.matrix[pixel + 2]),
7074
(x * 10 + 5, y * 10 + 5), 5, 0)
7175

7276
def render(self):
@@ -78,8 +82,7 @@ def render(self):
7882

7983
def gameloop(self):
8084
"""
81-
Loop through all the necessary stuff and end execution when Ctrl+C
82-
was hit.
85+
Loop through all the necessary stuff and end execution when Ctrl+C was hit.
8386
"""
8487
try:
8588
while True:
@@ -99,4 +102,4 @@ def gameloop(self):
99102

100103
if __name__ == '__main__':
101104
EMU = Emu()
102-
EMU.gameloop()
105+
EMU.gameloop()

pymlgame/__init__.py

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,74 @@
99
__email__ = '[email protected]'
1010
__status__ = 'Development'
1111

12+
import socket
13+
1214
from pymlgame.locals import *
1315
from pymlgame.screen import Screen
1416
from pymlgame.clock import Clock
1517
from pymlgame.surface import Surface
16-
from pymlgame.controller import Controller
18+
from pymlgame.controller import Controller
19+
20+
21+
def init(host='127.0.0.1', port=1337):
22+
"""
23+
Initialize pymlgame. This creates a controller thread that listens for game controllers and events.
24+
"""
25+
global ctlr
26+
ctlr = Controller(host, port + 1)
27+
ctlr.start()
28+
29+
30+
def get_events(maximum=10):
31+
"""
32+
Get all events since the last time you asked for them. You can define a maximum which is 10 by default.
33+
"""
34+
events = []
35+
for ev in range(0, maximum):
36+
try:
37+
if ctlr.queue.empty():
38+
break
39+
else:
40+
events.append(ctlr.queue.get_nowait())
41+
except NameError:
42+
not_initialized()
43+
events = False
44+
break
45+
return events
46+
47+
48+
def get_event():
49+
"""
50+
Get the next event in the queue if there is one.
51+
"""
52+
if not ctlr.queue.empty():
53+
return ctlr.queue.get_nowait()
54+
else:
55+
return False
56+
57+
58+
def controller_send(uid, event, data):
59+
"""
60+
Send an event to a connected controller. Use the pymlgame event type and the coorect data payload. For example is
61+
you want to send a message to the controller use the event pymlgame.MESSAGE and a string payload.
62+
63+
It returns the number of bytes send when everything went fine or False when something went wrong.
64+
"""
65+
try:
66+
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
67+
if uid in ctlr.controllers.keys():
68+
addr = ctlr.controllers[uid][0]
69+
if event == E_MESSAGE:
70+
return sock.sendto('/message/{}'.format(data).encode('utf-8'), (addr, 11338))
71+
elif event == E_RUMBLE:
72+
return sock.sendto('/rumble/{}'.format(data).encode('utf-8'), (addr, 11338))
73+
else:
74+
print('This UID ({}) doesn\'t exist.'.format(uid))
75+
return False
76+
except NameError:
77+
not_initialized()
78+
return False
79+
80+
81+
def not_initialized():
82+
print('pymlgame is not initialized correctly. Use pymlgame.init() first.')

pymlgame/locals.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,13 @@
1414
__status__ = 'Development'
1515

1616
# event types
17-
KEYUP = 0
18-
KEYDOWN = 1
19-
NEWCTLR = 2
20-
PING = 3
17+
E_KEYUP = 0
18+
E_KEYDOWN = 1
19+
E_NEWCTLR = 2
20+
E_PING = 3
21+
E_DISCONNECT = 4
22+
E_MESSAGE = 5
23+
E_RUMBLE = 6
2124

2225
# controller inputs
2326
CTLR_UP = 0
@@ -58,7 +61,4 @@
5861
GREY3 = (178, 178, 178)
5962
GREY2 = (204, 204, 204)
6063
GREY1 = (229, 229, 229)
61-
WHITE = (255, 255, 255)
62-
63-
64-
64+
WHITE = (255, 255, 255)

pymlgame/surface.py

Lines changed: 18 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -31,63 +31,57 @@ def __init__(self, width, height):
3131
self.matrix = None
3232
self.fill(pymlgame.BLACK)
3333

34-
def fill(self, color, brightness=0.1):
34+
def fill(self, color):
3535
"""
3636
Fill the whole screen with the given color.
3737
"""
38-
color = self.get_color(color, brightness)
39-
self.matrix = [[color for _ in range(self.height)]
40-
for _ in range(self.width)]
38+
self.matrix = [[color for _ in range(self.height)] for _ in range(self.width)]
4139

42-
def draw_dot(self, pos, color, brightness=0.1):
40+
def draw_dot(self, pos, color):
4341
"""
4442
Draw one single dot with the given color on the screen.
4543
"""
46-
realcolor = self.get_color(color, brightness)
4744
if 0 <= pos[0] < self.width and 0 <= pos[1] < self.height:
48-
self.matrix[pos[0]][pos[1]] = realcolor
45+
self.matrix[pos[0]][pos[1]] = color
4946

50-
def draw_line(self, start, end, color, brightness=0.1):
47+
def draw_line(self, start, end, color):
5148
"""
5249
Draw a line with the given color on the screen.
5350
"""
5451
def dist(p, a, b):
55-
return abs((b[0] - a[0]) * (a[1] - p[1]) - (a[0] - p[0]) *
56-
(b[1] - a[1])) / math.sqrt((b[0] - a[0])**2 +
57-
(b[1] - a[1])**2)
52+
return (abs((b[0] - a[0]) * (a[1] - p[1]) - (a[0] - p[0]) * (b[1] - a[1])) /
53+
math.sqrt((b[0] - a[0])**2 + (b[1] - a[1])**2))
5854

5955
points = []
6056
for x in range(min(start[0], end[0]), max(start[0], end[0]) + 1):
6157
for y in range(min(start[1], end[1]), max(start[1], end[1]) + 1):
6258
if dist((x, y), start, end) < 0.5:
6359
points.append((x, y))
6460
for point in points:
65-
self.draw_dot(point, color, brightness)
61+
self.draw_dot(point, color)
6662

67-
def draw_rect(self, pos, size, color, fillcolor=None, brightness=0.1):
63+
def draw_rect(self, pos, size, color, fillcolor=None):
6864
"""
6965
Draw a rectangle with the given color on the screen and optionally fill it with fillcolor.
7066
"""
7167
# draw top and botton line
7268
for x in range(size[0]):
73-
self.draw_dot((pos[0] + x, pos[1]), color, brightness)
74-
self.draw_dot((pos[0] + x, pos[1] + size[1] - 1), color, brightness)
69+
self.draw_dot((pos[0] + x, pos[1]), color)
70+
self.draw_dot((pos[0] + x, pos[1] + size[1] - 1), color)
7571
# draw left and right side
7672
for y in range(size[1]):
77-
self.draw_dot((pos[0], pos[1] + y), color, brightness)
78-
self.draw_dot((pos[0] + size[0] - 1, pos[1] + y), color, brightness)
73+
self.draw_dot((pos[0], pos[1] + y), color)
74+
self.draw_dot((pos[0] + size[0] - 1, pos[1] + y), color)
7975
# draw filled rect
8076
#TODO: find out if the rect is at least 3x3 to actually have a filling
8177
if fillcolor:
8278
for x in range(size[0] - 2):
8379
for y in range(size[1] - 2):
84-
self.draw_dot((pos[0] + 1 + x, pos[1] + 1 + y),
85-
fillcolor, brightness)
80+
self.draw_dot((pos[0] + 1 + x, pos[1] + 1 + y), fillcolor)
8681

87-
def draw_circle(self, pos, radius, color, fillcolor=None, brightness=0.1):
82+
def draw_circle(self, pos, radius, color, fillcolor=None):
8883
"""
89-
Draw a circle with the given color on the screen and optionally fill it
90-
with fillcolor.
84+
Draw a circle with the given color on the screen and optionally fill it with fillcolor.
9185
"""
9286
#TODO: This still produces rubbish but it's on a good way to success
9387
def dist(d, p, r):
@@ -106,7 +100,7 @@ def dist(d, p, r):
106100
pass
107101
# draw outline
108102
for point in points:
109-
self.draw_dot(point, color, brightness)
103+
self.draw_dot(point, color)
110104

111105
def blit(self, surface, pos=(0, 0)):
112106
"""
@@ -126,11 +120,4 @@ def replace_color(self, before, after):
126120
for x in range(self.width):
127121
for y in range(self.height):
128122
if self.matrix[x][y] == before:
129-
self.matrix[x][y] = after
130-
131-
@staticmethod
132-
def get_color(color, brightness=0.1):
133-
"""
134-
Returns the color with applied brightness level
135-
"""
136-
return tuple([math.floor(val * brightness) for val in color])
123+
self.matrix[x][y] = after

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,4 @@ def read(fname):
4747
platforms='any',
4848
license=__license__,
4949
packages=['pymlgame'],
50-
requires=['jsonrpclib-pelix'])
50+
requires=[,])

0 commit comments

Comments
 (0)