from pygame import display, image
from pygame.locals import *

from GameChild import *

class Display(GameChild):

    def __init__(self, game):
        GameChild.__init__(self, game)
        self.config = self.get_configuration().get_section("display")
        self.set_screen()
        self.set_caption()
        self.set_icon()
        self.subscribe_to(self.get_custom_event_id(), self.toggle_fullscreen)

    def set_screen(self, flags=0):
        self.screen = display.set_mode(self.config["dimensions"], flags)
        # robot spaceman ninja ranger

    def set_caption(self):
        display.set_caption(self.config["caption"])

    def set_icon(self):
        if self.get_configuration().has_option("display", "icon-path"):
            path = self.get_resource("display", "icon-path")
            display.set_icon(image.load(path).convert_alpha())

    def get_screen(self):
        return self.screen

    def get_size(self):
        return self.screen.get_size()

    def toggle_fullscreen(self, event):
        if self.is_command(event, "toggle-fullscreen"):
            screen = self.screen
            cpy = screen.convert()
            self.set_screen(self.screen.get_flags() ^ FULLSCREEN)
            screen.blit(cpy, (0, 0))
from os.path import exists, join, basename, normpath, abspath
from sys import argv

from pygame import mixer, event
from pygame.locals import *

import Game

class GameChild:

    def __init__(self, parent=None):
        self.parent = parent

    def get_game(self):
        current = self
        while not isinstance(current, Game.Game):
            current = current.parent
        return current

    def get_configuration(self, section=None, option=None):
        config = self.get_game().configuration
        if option and section:
            return config.get(section, option)
        if section:
            return config.get_section(section)
        return config

    def get_input(self):
        return self.get_game().input

    def get_screen(self):
        return self.get_game().display.get_screen()

    def get_audio(self):
        return self.get_game().audio

    def get_delegate(self):
        return self.get_game().delegate

    def get_resource(self, section, option):
        config = self.get_configuration()
        rel_path = config.get(section, option)
        for root in config.get("setup", "resources-search-path"):
            if self.is_shared_mode() and not self.is_absolute_path(root):
                continue
            path = join(root, rel_path)
            if exists(path):
                return path
        self.print_debug("Couldn't find resource: {0}, {1}".\
                                   format(section, option))

    def print_debug(self, statement):
        if self.is_debug_mode():
            print statement

    def is_absolute_path(self, path):
        return normpath(path) == abspath(path)

    def is_shared_mode(self):
        return "-s" in argv

    def subscribe_to(self, kind, callback):
        self.get_game().delegate.add_subscriber(kind, callback)

    def unsubscribe_from(self, kind, callback):
        self.get_game().delegate.remove_subscriber(kind, callback)

    def is_debug_mode(self):
        return "-d" in argv

    def get_custom_event_id(self):
        return globals()[self.get_configuration().get("event",
                                                      "custom-event-id")]

    def is_command(self, evt, cmd):
        name = self.get_configuration().get("event", "command-event-name")
        if not isinstance(cmd, list):
            cmd = [cmd]
        return evt.type == self.get_custom_event_id() and evt.name == name and \
               evt.command in cmd

    def post_command(self, command):
        name = self.get_configuration().get("event", "command-event-name")
        event.post(event.Event(self.get_custom_event_id(), name=name,
                               command=command))
import pygame

class Animation:

    def __init__(self, frame_duration, skip_frames=False):
        self.reset_ticks()
        self.updates_this_cycle = 1
        self.overflow = 0
        self.update_count = 1
        self.actual_frame_duration = 0
        self.target_frame_duration = frame_duration
        self.skip_frames = skip_frames
        self.stopping = False

    def reset_ticks(self):
        self.last_ticks = self.get_ticks()

    def play(self):
        while not self.stopping:
            self.advance_frame()
            self.update_frame_duration()
            self.update_overflow()
        self.stopping = False

    def advance_frame(self):
        while self.update_count > 0:
            self.sequence()
            self.update_count -= 1
            if not self.skip_frames:
                break

    def sequence(self):
        pass

    def update_frame_duration(self):
        last_ticks = self.last_ticks
        actual_frame_duration = self.get_ticks() - last_ticks
        last_ticks = self.get_ticks()
        wait_duration = self.get_configuration().get("display", "wait-duration")
        while actual_frame_duration < self.target_frame_duration:
            pygame.time.wait(wait_duration)
            actual_frame_duration += self.get_ticks() - last_ticks
            last_ticks = self.get_ticks()
        self.actual_frame_duration = actual_frame_duration
        self.last_ticks = last_ticks

    def get_ticks(self):
        return pygame.time.get_ticks()

    def update_overflow(self):
        self.update_count = 1
        target_frame_duration = self.target_frame_duration
        overflow = self.overflow
        overflow += self.actual_frame_duration - target_frame_duration
        while overflow > target_frame_duration:
            self.update_count += 1
            overflow -= target_frame_duration
        overflow = self.overflow

    def stop(self):
        self.stopping = True

    def clear_queue(self):
        self.update_count = 1
from pygame import event
from pygame.locals import *

from GameChild import *

class EventDelegate(GameChild):

    def __init__(self, game):
        GameChild.__init__(self, game)
        self.subscribers = dict()
        self.disable()

    def enable(self):
        self.enabled = True

    def disable(self):
        self.enabled = False

    def dispatch_events(self):
        if self.enabled:
            subscribers = self.subscribers
            for evt in event.get():
                kind = evt.type
                if kind in subscribers:
                    for subscriber in subscribers[kind]:
                        self.print_debug("Passing {0} to {1}".\
                                                   format(evt, subscriber))
                        subscriber(evt)
        else:
            event.pump()

    def add_subscriber(self, kind, callback):
        self.print_debug("Subscribing {0} to {1}".\
                                   format(callback, kind))
        subscribers = self.subscribers
        if kind not in subscribers:
            subscribers[kind] = list()
        subscribers[kind].append(callback)

    def remove_subscriber(self, kind, callback):
        self.subscribers[kind].remove(callback)
3.235.65.220
3.235.65.220
3.235.65.220
 
January 23, 2021

I wanted to document this chat-controlled robot I made for Babycastles' LOLCAM📸 that accepts a predefined set of commands like a character in an RPG party 〰 commands like walk, spin, bash, drill. It can also understand donut, worm, ring, wheels, and more. The signal for each command is transmitted as a 24-bit value over infrared using two Arduinos, one with an infrared LED, and the other with an infrared receiver. I built the transmitter circuit, and the receiver was built into the board that came with the mBot robot kit. The infrared library IRLib2 was used to transmit and receive the data as a 24-bit value.


fig. 1.1: the LEDs don't have much to do with this post!

I wanted to control the robot the way the infrared remote that came with the mBot controlled it, but the difference would be that since we would be getting input from the computer, it would be like having a remote with an unlimited amount of buttons. The way the remote works is each button press sends a 24-bit value to the robot over infrared. Inspired by Game Boy Advance registers and tracker commands, I started thinking that if we packed multiple parameters into the 24 bits, it would allow a custom move to be sent each time, so I wrote transmitter and receiver code to process commands that looked like this:

bit
name
description
00
time
multiply by 64 to get duration of command in ms
01
02
03
04
left
multiply by 16 to get left motor power
05
06
07
08
right
multiply by 16 to get right motor power
09
10
11
12
left sign
0 = left wheel backward, 1 = left wheel forward
13
right sign
0 = right wheel forward, 1 = right wheel backward
14
robot id
0 = send to player one, 1 = send to player two
15
flip
negate motor signs when repeating command
16
repeats
number of times to repeat command
17
18
19
delay
multiply by 128 to get time between repeats in ms
20
21
22
23
swap
swap the motor power values on repeat
fig 1.2: tightly stuffed bits

The first command I was able to send with this method that seemed interesting was one that made the mBot do a wheelie.

$ ./send_command.py 15 12 15 1 0 0 0 7 0 1
sending 0xff871fcf...


fig 1.3: sick wheels

A side effect of sending the signal this way is any button on any infrared remote will cause the robot to do something. The star command was actually reverse engineered from looking at the code a random remote button sent. For the robot's debut, it ended up with 15 preset commands (that number is in stonks 📈). I posted a highlights video on social media of how the chat controls turned out.

This idea was inspired by a remote frog tank LED project I made for Ribbit's Frog World which had a similar concept: press a button, and in a remote location where 🐸 and 🐠 live, an LED would turn on.


fig 2.1: saying hi to froggo remotely using an LED

😇 The transmitter and receiver Arduino programs are available to be copied and modified 😇