Exemple #1
0
            await leds.brighter()
        elif not alarmOn and leds.on:
            await leds.dim()
        else:
            await asyncio.sleep(1)

def main():
    loop = asyncio.get_event_loop()
    loop.create_task(ledControl())
    loop.create_task(main_loop())
    loop.create_task(refresh())
    loop.run_forever()

try:
    main()
    
except IOError as e:
    logging.info(e)
    
except KeyboardInterrupt:    
    logging.info("ctrl + c:")
    
finally:
    screen.clear()
    t.sleep(4)
    epd7in5.epdconfig.module_exit()
    sensors.cleanup()
    leds.stop()
    exit()

Exemple #2
0
 def __init__(self, fretcount):
     '''Class constructor'''
     Screen.clear() # Clear the screen
     self.screen = Screen()
     self.fretcount = fretcount
Exemple #3
0
class Game:
    def __init__(self):
        from Screen import Screen
        self.screen = Screen()
        self.grid = self.create_grid().randomize()
        self.PAUSE = False

    def create_grid(self):
        from Grid import Grid
        return Grid(self.screen.num_rows(), self.screen.num_cols())

    def draw_grid(self):
        self.screen.clear()
        self.screen.draw_grid(self.grid)

    def determine_new_cell_state(self, row, col):
        # gegeven een cel[row][col], bepaal de nieuwe state van de cel aan de hand van zijn buren
        num_alive_neighbours = self.grid.get_alive_neighbours(row, col)
        cell_value = self.grid.get_value(row, col)
        if cell_value == Constants.ALIVE:
            if num_alive_neighbours < 2:  # rule 1: underpopulation: levende cel gaat dood uit eenzaamheid
                return Constants.DEATH
            if num_alive_neighbours == 2 or num_alive_neighbours == 3:
                return Constants.ALIVE  # rule 2: stay alive: levende cel heeft voldoende levende buren
            if num_alive_neighbours > 3:  # rule 3: overpopulation: cel gaat dood indien meer dan 3 levende buren
                return Constants.DEATH
        elif cell_value == Constants.DEATH:
            if num_alive_neighbours == 3:  # rule 4: reproduction: dode cel komt tot leven met 3 levende buren
                return Constants.ALIVE
        return cell_value  # geen wijziging

    def update_generation(self):
        # maak een nieuwe grid en pas de regels toe op basis van de oude generatie
        new_grid = self.create_grid()
        for row in range(self.grid.num_rows):
            for col in range(self.grid.num_cols):
                new_cell_state = self.determine_new_cell_state(row, col)
                new_grid.set_value(row, col, new_cell_state)
        self.grid = new_grid

    def load_file(self,
                  filename,
                  offset_row=Constants.OFFSET_ROW,
                  offset_col=Constants.OFFSET_COL):
        # lees een rle file in en plaats deze in grid vanaf offset[row][col]
        from RleReader import RleReader
        self.screen.clear()
        self.grid = self.create_grid()
        RleReader.read_from_file(self.grid, filename, offset_row, offset_col)
        self.screen.draw_grid(self.grid)
        self.PAUSE = True

    def save_file(self, filename):
        from RleWriter import RleWriter
        RleWriter.save_to_file(filename, self.grid)

    def handle_events(self):
        def key_file(key):
            num = key - pygame.K_0
            name = "./data/file_{0}.rle".format(num)
            return name

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:  # quit
                    sys.exit()
                elif event.key == pygame.K_p:  # pause
                    self.PAUSE = not self.PAUSE
                elif event.key == pygame.K_s:  # save
                    self.save_file("./data/pipo.rle")
                elif event.key == pygame.K_l:  # load
                    self.load_file("./data/pipo.rle", 0, 0)
                elif event.key == pygame.K_r:  # randomize
                    self.grid = self.create_grid().randomize()
                elif event.key == pygame.K_c:  # clear
                    self.grid.clear()
                elif event.key == pygame.K_t:  # single step if pause
                    self.update_generation()
                    self.screen.draw_grid(self.grid)
                elif event.key in [
                        pygame.K_0,  # load key 1-0 file
                        pygame.K_1,
                        pygame.K_2,
                        pygame.K_3,
                        pygame.K_4,
                        pygame.K_5,
                        pygame.K_6,
                        pygame.K_7,
                        pygame.K_8,
                        pygame.K_9
                ]:
                    self.load_file(key_file(event.key))
            elif event.type == pygame.QUIT:
                sys.exit()

    def run(self):
        while True:
            self.handle_events()
            if not self.PAUSE:
                self.update_generation()
                self.screen.draw_grid(self.grid)
            self.screen.cap_frame_rate()
Exemple #4
0
class Game:

    gamepad = None
    player = None
    screen = None
    entityManager = None
    world = None

    FRAMES_PER_SECOND = 25

    game_is_running = False

    def __init__(self):
        print("Press Ctrl-C to quit")

        self.gamepad = GamePad()
        self.screen = Screen()
        self.entityManager = EntityManager()
        self.player = Player(self)
        self.world = World(self)
        self.entityManager.add(self.player)

    def update(self, dt):

        self.gamepad.update()

        if (self.gamepad.pressed[GAMEPAD_BUTTON.START]):
            self.game_is_running = False
            return

        self.world.update()
        self.entityManager.update(dt)

    def draw(self):
        self.screen.clear()
        self.world.draw()
        self.entityManager.draw()
        self.screen.draw()

    def start(self):
        print("GO!")
        self.loop()

    def loop(self):

        self.game_is_running = True

        lastFrameTime = time.time()

        try:
            while self.game_is_running:
                currentTime = time.time()
                dt = currentTime - lastFrameTime

                sleepTime = 1. / self.FRAMES_PER_SECOND - (currentTime -
                                                           lastFrameTime)

                if sleepTime > 0:
                    time.sleep(sleepTime)

                self.update(dt)
                self.draw()

                lastFrameTime = currentTime
            self.screen.off()
        except KeyboardInterrupt:
            self.screen.off()
            sys.exit()
Exemple #5
0
class Display:

    FONT_CHAR_WIDTH = 3
    FONT_CHAR_HEIGHT = 5
    SERIAL_BAUD_RATE = 115200
    SERIAL_ADDR = "/dev/ttyAMA0"

    def __init__(self):
        if (PLATFORM_PI):
            self._serial_port = Serial(Display.SERIAL_ADDR,
                                       Display.SERIAL_BAUD_RATE)
            if (self._serial_port.is_open() == False):
                self._serial_port.open()

        rows, columns = subprocess.check_output(['stty', 'size']).split()
        self._window_dims = np.array([int(columns), int(rows)], dtype=int)

        # The distance (in characters) between the centre positions of 7 seg digits
        self._num_char_centre_dist = int(Display.FONT_CHAR_WIDTH / 2) * 2 + 2

        self._net_pos_x = int(self._window_dims[0] / 2)
        self._screen = Screen(self._window_dims)

        print(colour_reset_code())

        # Reset cursor position
        self.print_output("\033[2J")

        # Hide cursor code
        self.print_output(cursor_visibilty_code(False))

    def print_output(self, str):
        if (PLATFORM_PI and not PRINT_TO_TERMINAL):
            self._serial_port.write(bytes(str, 'ASCII'))
        else:
            print(str)

    def begin(self):
        self._screen.clear()

    def end(self):
        self.print_output(self._screen.get_output_string())
        self._screen.swap_buffers()

    def draw_background(self):
        self.draw_net()

    def draw_net(self):
        for i in range(1, self._window_dims[1]):
            if ((i + 1) % 3 == 1 or (i + 2) % 3 == 1):
                self._screen.set_colour_idx_at(
                    list(COLOURS.keys()).index("net"), [self._net_pos_x, i])

    def draw_score(self, score, pos_centre):
        digits = [int(c) for c in str(score)]
        num_digits = len(digits)

        pos_centre_x = pos_centre[0]
        first_digit_pos_x = pos_centre_x - ((num_digits - 1) *
                                            (Display.FONT_CHAR_WIDTH + 1) // 2)

        for i in range(0, num_digits):
            digit_pos_centre = np.array([
                first_digit_pos_x + i * self._num_char_centre_dist,
                pos_centre[1]
            ])
            self._draw_7_seg_number(digits[i], digit_pos_centre)

    def draw_player(self, player):
        paddle = player.paddle
        pos = np.around(paddle.position).astype(int)
        size = int(paddle.size)

        # Draw paddle
        for i in range(-size // 2, size // 2):
            p = np.around(np.array(pos) + np.array([0, i])).astype(int)
            colour_name = "paddle" + ("Left"
                                      if player.side == Side.LEFT else "Right")
            colour_code = list(COLOURS.keys()).index(colour_name)
            self._screen.set_colour_idx_at(colour_code, p)

    def draw_ball(self, ball):
        pos = np.around(ball.position).astype(int)
        self._screen.set_colour_idx_at(list(COLOURS.keys()).index("ball"), pos)

    def draw_win_screen(self, player):
        start_pos_tl = np.array([(self._window_dims[0] - win_text_width) // 2,
                                 (self._window_dims[1] - win_text_height) // 2
                                 ])
        counter = 0

        for i in range(0, len(win_text_rle)):
            if (i % 2 == 0):
                for j in range(0, win_text_rle[i]):
                    x = counter % win_text_width
                    y = (counter - x) // win_text_width
                    counter += 1
                    p = start_pos_tl + np.array([x + 1, y + 1])
                    self._screen.set_colour_idx_at(
                        list(COLOURS.keys()).index("text"), p)
            else:
                counter += win_text_rle[i]

        self._draw_7_seg_number(int(player.side) + 1, self._window_dims // 2)

    def _draw_7_seg_number(self, num, pos_centre):
        if (num < 0 or num > 9):
            print(
                "7-segment display can only display single-digit numbers (got "
                + str(num) + ")")
            input()
            return

        # Each number should be drawn relative to the CENTRE of the 7 segment block
        pos_centre[0] -= Display.FONT_CHAR_WIDTH // 2 + 1
        pos_centre[1] -= Display.FONT_CHAR_HEIGHT // 2 + 1

        for y in range(0, 5):
            for x in range(0, 3):
                pos = np.array(pos_centre).astype(int) + np.array(
                    [x + 1, y + 1])
                if (digits[num][y * 3 + x] == 1):
                    self._screen.set_colour_idx_at(
                        list(COLOURS.keys()).index("text"), pos)

    def close(self):
        if (PLATFORM_PI):
            self._serial_port.close()

        self.print_output(cursor_visibilty_code(True))
        self.print_output(colour_reset_code())
        self.print_output(cursor_reset_code())

    @property
    def window_dims(self):
        return self._window_dims

    @property
    def net_pos_x(self):
        return self._net_pos_x
Exemple #6
0
class Interpreter(object):

    digits = {
        0x0: [0xf0, 0x90, 0x90, 0x90, 0xf0],
        0x1: [0x20, 0x60, 0x20, 0x20, 0x70],
        0x2: [0xf0, 0x10, 0xf0, 0x80, 0xf0],
        0x3: [0xf0, 0x10, 0xf0, 0x10, 0xf0],
        0x4: [0x90, 0x90, 0xf0, 0x10, 0x10],
        0x5: [0xf0, 0x80, 0xf0, 0x10, 0xf0],
        0x6: [0xf0, 0x80, 0xf0, 0x90, 0xf0],
        0x7: [0xf0, 0x10, 0x20, 0x40, 0x40],
        0x8: [0xf0, 0x90, 0xf0, 0x90, 0xf0],
        0x9: [0xf0, 0x90, 0xf0, 0x10, 0xf0],
        0xa: [0xf0, 0x90, 0xf0, 0x90, 0x90],
        0xb: [0xe0, 0x90, 0xf0, 0x10, 0xf0],
        0xc: [0xf0, 0x80, 0x80, 0x80, 0xf0],
        0xd: [0xe0, 0x90, 0x90, 0x90, 0xe0],
        0xe: [0xf0, 0x80, 0xf0, 0x80, 0xf0],
        0xf: [0xf0, 0x80, 0xf0, 0x80, 0x80]
    }

    def __init__(self, rom_name, scale=5):
        self.screen = Screen(scale=scale)

        self.rom_name = None
        self.registers = np.zeros(16, dtype=np.uint8)
        self.I = np.zeros(1, dtype=np.uint16)
        self.mem = np.zeros(4096, dtype=np.uint8)
        self.digit_locs = {d: 5 * d for d in range(16)}

        self.keyboard = np.zeros(16, dtype=np.uint8)

        self.stack = []

        self.dt = np.zeros(1, dtype=np.uint8)
        self.st = np.zeros(1, dtype=np.uint8)

        self.pc = 0x200

        self.clock = pygame.time.Clock()
        self.clock_speed = 600  # Hz
        self.cycle = 0

        self.open(rom_name)

    def reset_mem(self):
        self.pc = 0x200

        self.mem[:] = 0

        for d in range(16):
            self.mem[5 * d:5 * d + 5] = self.digits[d]

    def open(self, rom_name):
        self.rom_name = rom_name
        self.screen.set_caption(rom_name)

        self.reset_mem()

        with open(f".//rom//{rom_name}.ch8", "rb") as f:
            i = 0x200
            byte = f.read(1)
            while byte:
                self.mem[i] = int.from_bytes(byte, byteorder="big")
                byte = f.read(1)

                i += 1

    def handle_events(self):

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:

                for i in range(16):
                    if event.key == getattr(pygame,
                                            "K_" + "x123qweasdzc4rfv"[i]):
                        self.keyboard[i] = 1
                        break

            elif event.type == pygame.KEYUP:
                for i in range(16):
                    if event.key == getattr(pygame,
                                            "K_" + "x123qweasdzc4rfv"[i]):
                        self.keyboard[i] = 0
                        break

    def get_key(self):
        print("GET KEY")
        while True:
            self.handle_events()

            for i in range(16):
                if self.keyboard[i]:
                    return i

            self.clock.tick(self.clock_speed)

    def run(self):

        while True:

            self.execute()
            self.cycle = (self.cycle + 1) % self.clock_speed

            if self.cycle % 60 == 0:
                self.handle_events()

                if np.any(self.dt):
                    self.dt -= 1

                if np.any(self.st):
                    self.st -= 1
                    winsound.Beep(2500, 100)

            self.clock.tick(self.clock_speed)

    def execute(self):
        instruction = int(0x100 * self.mem[self.pc] + self.mem[self.pc + 1])
        self.pc += 2

        x = (instruction & 0x0f00) // 0x0100
        y = (instruction & 0x00f0) // 0x0010

        # CLS
        if instruction == 0x00e0:
            self.screen.clear()

        # RET
        elif instruction == 0x00ee:
            self.pc = self.stack.pop(-1)

        # JP
        elif instruction & 0xf000 == 0x1000:
            self.pc = instruction & 0x0fff

        # CALL
        elif instruction & 0xf000 == 0x2000:
            self.stack.append(self.pc)  # todo: +2 or no?
            assert len(self.stack) <= 16
            self.pc = instruction & 0x0fff

        # SE
        elif instruction & 0xf000 == 0x3000:
            if self.registers[x] == (instruction & 0x00ff):
                self.pc += 2

        # SNE
        elif instruction & 0xf000 == 0x4000:
            if self.registers[x] != (instruction & 0x00ff):
                self.pc += 2

        # SE
        elif instruction & 0xf000 == 0x5000:
            if self.registers[x] == self.registers[y]:
                self.pc += 2

        # LD
        elif instruction & 0xf000 == 0x6000:
            self.registers[x] = instruction & 0x00ff

        # ADD
        elif instruction & 0xf000 == 0x7000:
            self.registers[x] += instruction & 0x00ff

        elif instruction & 0xf000 == 0x8000:

            # LD
            if instruction & 0x000f == 0x0000:
                self.registers[x] = self.registers[y]

            # OR
            elif instruction & 0x000f == 0x0001:
                self.registers[x] |= self.registers[y]

            # AND
            elif instruction & 0x000f == 0x0002:
                self.registers[x] &= self.registers[y]

            # XOR
            elif instruction & 0x000f == 0x0003:
                self.registers[x] ^= self.registers[y]

            # ADD
            elif instruction & 0x000f == 0x0004:
                self.registers[0xf] = int(self.registers[x]) + int(
                    self.registers[y]) > 255
                self.registers[x] += self.registers[y]

            # SUB
            elif instruction & 0x000f == 0x0005:
                self.registers[0xf] = self.registers[x] > self.registers[y]
                self.registers[x] -= self.registers[y]

            # SHR
            elif instruction & 0x000f == 0x0006:
                self.registers[0xf] = self.registers[x] & 0b00000001
                self.registers[x] //= 2

            # SUBN
            elif instruction & 0x000f == 0x0007:
                self.registers[0xf] = self.registers[x] < self.registers[y]
                self.registers[x] = self.registers[y] - self.registers[x]

            # SHL
            elif instruction & 0x000f == 0x000e:
                self.registers[0xf] = self.registers[x] & 0b10000000
                self.registers[x] *= 2

            else:
                raise Exception(f"Unknown instruction: {hex(instruction)}")

        # SNE
        elif instruction & 0xf000 == 0x9000:
            if self.registers[x] != self.registers[y]:
                self.pc += 2

        # LD I
        elif instruction & 0xf000 == 0xa000:
            self.I[0] = instruction & 0x0fff

        # JP V0
        elif instruction & 0xf000 == 0xb000:
            self.pc = (instruction & 0x0fff) + self.registers[0x0]

        # RND
        elif instruction & 0xf000 == 0xc000:
            self.registers[x] = random.randint(0, 255) & (instruction & 0x00ff)

        # DRW
        elif instruction & 0xf000 == 0xd000:
            self.registers[0xf] = self.screen.draw(
                self.mem[int(self.I[0]):int(self.I[0]) +
                         (instruction & 0x000f)],
                (self.registers[x], self.registers[y]))

        elif instruction & 0xf000 == 0xe000:

            # SKP
            if instruction & 0x00ff == 0x009e:
                if self.keyboard[self.registers[x]]:
                    self.pc += 2

            # SKNP
            elif instruction & 0x00ff == 0x00a1:
                if not self.keyboard[self.registers[x]]:
                    self.pc += 2

            else:
                raise Exception(f"Unknown instruction: {hex(instruction)}")

        elif instruction & 0xf000 == 0xf000:

            # LD
            if instruction & 0x00ff == 0x0007:
                self.registers[x] = self.dt[0]

            # LD
            elif instruction & 0x00ff == 0x000a:
                self.registers[x] = self.get_key()

            # LD DT
            elif instruction & 0x00ff == 0x0015:
                self.dt[0] = self.registers[x]

            # LD ST
            elif instruction & 0x00ff == 0x0018:
                self.st[0] = self.registers[x]

            # ADD I
            elif instruction & 0x00ff == 0x001e:
                self.I[0] += self.registers[x]

            # LD F
            elif instruction & 0x00ff == 0x0029:
                self.I[0] = self.digit_locs[int(self.registers[x])]

            # LD B
            elif instruction & 0x00ff == 0x0033:
                decimal = str(int(self.registers[x])).zfill(3)
                for i in range(3):
                    self.mem[int(self.I[0]) + i] = int(decimal[i])

            # LD [I]
            elif instruction & 0x00ff == 0x0055:
                for i in range((instruction & 0x0f00) // 0x0100 + 1):
                    self.mem[int(self.I[0]) + i] = self.registers[i]

            # LD
            elif instruction & 0x00ff == 0x0065:
                for i in range((instruction & 0x0f00) // 0x0100 + 1):
                    self.registers[i] = self.mem[int(self.I[0]) + i]

            else:
                raise Exception(f"Unknown instruction: {hex(instruction)}")

        else:
            raise Exception(f"Unknown instruction: {hex(instruction)}")