from pygame import font

from GameChild import *

class Font(font.Font, GameChild):

    def __init__(self, parent, size):
        GameChild.__init__(self, parent)
        font.Font.__init__(self, self.get_resource("font", "path"), size)
import os
import time

from pygame import image

from GameChild import *
from Input import *

class ScreenGrabber(GameChild):

    def __init__(self, game):
        GameChild.__init__(self, game)
        self.subscribe_to(Input.command_event, self.save_display)

    def save_display(self, event):
        if event.command == "capture-screen":
            directory = self.get_configuration()["screen-capture-save-dir"]
            if not os.path.exists(directory):
                os.mkdir(directory)
            name = time.ctime().replace(" ", "-") + ".png"
            path = os.path.join(directory, name)
            capture = image.save(self.get_screen(), path)
from esp_hadouken.sprite.Sprite import *
from esp_hadouken.pgfw.GameChild import *

class Diortem(Sprite):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.init_sprite()

    def init_sprite(self):
        configuration = self.get_configuration()
        image_path = self.get_resource("diortem", "image-path")
        Sprite.__init__(self, self.parent, image_path, self.parent)
from os import walk, remove
from os.path import sep, join, exists, realpath, relpath
from re import findall

from Configuration import *

class Setup:

    config = Configuration(local=True)

    @classmethod
    def remove_old_mainfest(self):
        path = "MANIFEST"
        if exists(path):
            remove(path)

    @classmethod
    def build_package_list(self):
        packages = []
        for root, dirs, files in walk("esp_hadouken"):
            packages.append(root.replace(sep, "."))
        return packages

    @classmethod
    def build_data_map(self):
        install_root = self.config["resources-install-path"]
        include = [(install_root, ["config", "hi-scores"])]
        exclude = map(realpath,
                      [".git", "esp_hadouken", "resources/local", "dist",
                       "build"])
        for root, dirs, files in walk("."):
            removal = []
            for directory in dirs:
                if realpath(join(root, directory)) in exclude:
                    removal.append(directory)
            for directory in removal:
                dirs.remove(directory)
            if root != ".":
                destination = join(install_root, relpath(root))
                listing = []
                for file_name in files:
                    listing.append(join(root, file_name))
                include.append((destination, listing))
        return include

    @classmethod
    def translate_title(self):
        return self.config["game-title"].replace(" ", "-")

    @classmethod
    def build_description(self):
        return "\n%s\n%s\n%s" % (file("description").read(),
                                 "Changelog\n=========",
                                 self.translate_changelog())

    @classmethod
    def translate_changelog(self):
        translation = ""
        for line in file("changelog"):
            line = line.strip()
            if line.startswith("esp-hadouken"):
                version = findall("\((.*)\)", line)[0]
                translation += "\n%s\n%s\n" % (version, "-" * len(version))
            elif line and not line.startswith("--"):
                if line.startswith("*"):
                    translation += line + "\n"
                else:
                    translation += "  " + line + "\n"
        return translation
import re
import os
from sys import argv
from os.path import exists, join

import pygame

class Configuration(dict):

    assignment_operator = "="
    comments_operator = "#"
    field_separator = ","
    keys_prefix = "keys_"
    
    int_parameters = [
        "display-frame-duration", "display-wait-duration",
        "introduction-diortem-y", "overworld-toy-y", "overworld-wall-y",
        "overworld-dot-y", "joy-advance", "overworld-bandits-margin",
        "ending-score-size", "background-music-channel-id",
        "octo-level-min-gap", "octo-level-barrier-height",
        "octo-level-scroll-speed", "level-checker-width",
        "tooth-level-scroll-speed", "circulor-level-scroll-speed",
        "diortem-level-scroll-speed", "horse-level-scroll-speed",
        "horse-level-step-limit", "level-exit-alpha", "joy-pause",
        "introduction-prompt-size", "introduction-controls-height",
        "introduction-controls-size", "introduction-controls-offset",
        "introduction-controls-alpha", "timer-max-time",
        "scoreboard-palette-length", "scoreboard-prompt-margin",
        "scoreboard-prompt-text-size", "scoreboard-palette-brightness",
        "ending-input-message-y", "ending-input-message-size",
        "scoreboard-padding", "scoreboard-row-height",
        "scoreboard-interval-length", "scoreboard-width", "scoreboard-alpha",
        "scoreboard-rank-size", "scoreboard-total-size",
        "scoreboard-initials-size", "scoreboard-split-size",
        "scoreboard-initials-margin", "scoreboard-heading-height",
        "scoreboard-heading-checker-count", "scoreboard-heading-margin",
        "scoreboard-heading-title-size", "scoreboard-heading-title-indent",
        "scoreboard-heading-title-offset", "distance-text-size"]

    float_parameters = [
        "dot-thrust-magnitude", "dot-initial-blink-frequency",
        "dot-max-blink-frequency", "introduction-entrance-speed",
        "introduction-exit-speed", "level-max-dot-displacement",
        "tooth-level-switch-frequency", "circulor-level-speed",
        "distance-modifier"]

    list_parameters = [
        "keys-up", "keys-right", "keys-down", "keys-left", "keys-quit",
        "keys-pause", "sprite-inner-palette", "sprite-outer-palette",
        "keys-advance", "keys-capture-screen", "keys-reset",
        "octo-level-palette", "horse-level-palette", "diortem-level-palette",
        "circulor-level-palette", "tooth-level-palette", "keys-pause",
        "keys-mute", "keys-skip", "keys-previous", "keys-next",
        "game-platforms", "keys-fullscreen"]

    tuple_parameters = [
        "introduction-toy-position", "introduction-prompt-position",
        "display-dimensions", "octo-level-dimensions",
        "octo-level-dot-position", "octo-level-bandit-position",
        "octo-level-rect-position", "diortem-level-dimensions",
        "diortem-level-dot-position", "diortem-level-bandit-position",
        "horse-level-dimensions", "horse-level-dot-position",
        "horse-level-bandit-position", "circulor-level-dimensions",
        "circulor-level-dot-position", "circulor-level-bandit-position",
        "tooth-level-dimensions", "tooth-level-dot-position",
        "tooth-level-bandit-position", "ending-toy-size", "ending-toy-position",
        "ending-plate-position", "octo-level-void-padding",
        "octo-level-spawn-range", "level-blink-frequency-range",
        "tooth-level-void-padding", "tooth-level-radius-range",
        "tooth-level-spawn-range", "diortem-level-void-padding",
        "diortem-level-segment-width-range", "diortem-level-shift-range",
        "diortem-level-segment-height-range", "diortem-level-leg-range",
        "circulor-level-height-range", "circulor-level-base-range",
        "circulor-level-void-padding", "horse-level-size-range",
        "horse-level-void-padding", "scoreboard-prompt-dimensions",
        "scoreboard-column-widths", "distance-dimensions"]

    boolean_parameters = []
    true_values = ["yes", "y", "true", "t", "1"]

    path_values = [
        "dot-image-path", "introduction-bg-path", "toy-image-path",
        "overworld-bg-path", "overworld-wall-path", "screen-capture-save-dir",
        "overworld-bandits-path", "level-bandit-sprite-path", "ending-bg-path",
        "ending-plate-path", "introduction-audio-path", "overworld-audio-path",
        "level-audio-path", "ending-audio-path", "horse-level-maze-path",
        "level-failure-sound", "level-success-sound", "sfx-path",
        "level-exit-path", "pause-image-path", "display-icon-path", "font-path",
        "resources-install-path", "scoreboard-scores-path"]
    
    def __init__(self, local=False):
        self.local = local
        self.set_file_path()
        self.parse()

    def set_file_path(self):
        path = "config"
        installed_path = join("/usr/local/share/esp-hadouken/", path)
        if exists(installed_path) and self.use_installed_file():
            path = installed_path
        self.file_path = path

    def use_installed_file(self):
        if "-l" in argv or self.local:
            return False
        return True
    
    def parse(self):
        for line in file(self.file_path):
            line = line.strip()
            if len(line) > 0 and line[0] != self.comments_operator:
                (lval, rval) = map(
                    str.strip, line.split(self.assignment_operator))
                if lval in self.int_parameters:
                    rval = int(rval)
                if lval in self.float_parameters:
                    rval = float(rval)
                if lval in self.boolean_parameters:
                    rval = True if self.is_true_value(rval) else False
                if lval in self.path_values:
                    rval = self.translate_path(rval)
                if lval in self.tuple_parameters:
                    rval = eval(rval)
                if lval in self.list_parameters:
                    rval = map(str.strip, rval.split(self.field_separator))
                    if self.is_key_assignment(lval):
                        rval = map(lambda key: getattr(pygame, key), rval)
                self[lval] = rval

    def translate_path(self, rval):
        new = ""
        if rval[0] == "/":
            new += "/"
        return new + os.path.join(*rval.split("/"))

    def is_true_value(self, rval):
        return rval.lower() in self.true_values

    def is_key_assignment(self, lval):
        pattern = "^" + self.keys_prefix + "*"
        return re.match(pattern, lval) is not None
216.73.216.51
216.73.216.51
216.73.216.51
 
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 😇