aboutsummaryrefslogtreecommitdiff
path: root/turtetris_master/led_output.py
blob: ecc4d57cfed359f051cc30d18509ccd47cafb9ab (plain)
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
import zmq
import json
import copy


class Matrix:
    "Leds matrix"

    def __init__(self):
        "Establish connection to matrix"
        self.width = 12
        self.height = 10
        self.__mat__ = [None]*10
        for x in range(10):
            self.__mat__[x] = [None]*12
            for y in range(12):
                self.__mat__[x][y] = '000000'
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.PUB)
        self.socket.bind('tcp://*:4444')

    def display(self):
        "Display matrix to leds"
        for i in range(0, 10):
            self.socket.send_string('line' + str(i) + ' ' +
                                    json.dumps(self.__mat__[i]))

    def pixel(self, x, y, color):
        "Set pixel in matrix"
        if x < 0 or x > 11 or y < 0 or y > 9:
            raise Exception('Pixel out of matrix')
        self.__mat__[y][x] = color

    def fill(self, color):
        "Fill whole matrix with given color"
        for x in range(self.width):
            for y in range(self.height):
                self.pixel(x, y, color)

    def set_matrix(self, matrix):
        "Set given matrix as matrix"
        for x in range(self.width):
            for y in range(self.height):
                self.pixel(x, y, matrix[y][x])

    def copy_matrix(self):
        "Return copy of current matrix"
        return copy.deepcopy(self.__mat__)

    def matrix_diff(self, matrix):
        """
        Returns set of changes in matrix
        Every item in set is dictionary with following items:
            x: X position of led
            y: Y position of led
            color: string defining color of given led
        """
        change = list()
        for x in range(self.width):
            for y in range(self.height):
                if matrix[y][x] != self.__mat__[y][x]:
                    change.append({
                        'x': x,
                        'y': y,
                        'color': self.__mat__[y][x]
                        })
        return change

    def matrix_apply_diff(self, diff):
        "Apply diff generated by matrix_diff"
        for change in diff:
            self.pixel(change['x'], change['y'], change['color'])