from os import system, sep, walk, remove
from os.path import basename, join, exists
from shutil import copy, copytree, rmtree
from distutils.core import setup
from zipfile import ZipFile

import py2exe

from esp_hadouken.Setup import *

origIsSystemDLL = py2exe.build_exe.isSystemDLL
def isSystemDLL(pathname):
    if basename(pathname).lower() in ("libogg-0.dll", "sdl_ttf.dll"):
        return 0
    return origIsSystemDLL(pathname)
py2exe.build_exe.isSystemDLL = isSystemDLL

destination = "dist/win/"

setup(windows=[{"script": "esp-hado",
                "icon_resources": [(1, Setup.config["game-icon-path"])]
                }],
      options={"py2exe": {"packages": Setup.build_package_list(),
                          "dist_dir": destination}})

def ignore_files(src, names):
    ignored = []
    if src == "aud":
        ignored += ["uncompressed", "mod"]
    if src == "img":
        ignored += ["local"]
    return ignored

for path in ["config", "Basic.ttf", "hi-scores", "README", "changelog"]:
    copy(path, destination)

for path in ["aud", "img"]:
    folder = join(destination, path)
    if not exists(folder):
        copytree(path, folder, ignore=ignore_files)

rmtree("build")

def create_archive():
    title = Setup.translate_title() + "-" + Setup.config["game-version"] + "-win"
    archive_name = title + ".zip"
    archive = ZipFile(archive_name, "w")
    for root, dirs, names in walk(destination):
        for name in names:
            path = join(root, name)
            archive.write(path, path.replace(destination, title + sep))
    archive.close()
    copy(archive_name, "dist")
    remove(archive_name)
    rmtree(destination)

create_archive()
from pygame import event, joystick as joy, key as keyboard
from pygame.locals import *

from GameChild import *

class Input(GameChild):

    command_event = USEREVENT + 7

    def __init__(self, game):
        GameChild.__init__(self, game)
        self.joystick = Joystick()
        self.unsuppress()
        self.subscribe_to_events()
        self.build_key_map()

    def subscribe_to_events(self):
        self.subscribe_to(KEYDOWN, self.translate_key_press)
        self.subscribe_to(JOYBUTTONDOWN, self.translate_joy_button)
        self.subscribe_to(JOYAXISMOTION, self.translate_axis_motion)

    def suppress(self):
        self.suppressed = True

    def unsuppress(self):
        self.suppressed = False

    def build_key_map(self):
        key_map = {}
        for key, value in self.get_configuration().iteritems():
            group, command = key.split("-", 1)
            if group == "keys":
                key_map[command] = value
        self.key_map = key_map

    def translate_key_press(self, evt):
        if self.is_debug_mode():
            print "You pressed %i, suppressed => %s" % (evt.key, self.suppressed)
        if not self.suppressed:
            key = evt.key
            for command, keys in self.key_map.iteritems():
                if key in keys:
                    self.post_command(command)

    def post_command(self, name):
        if self.is_debug_mode():
            print "Posting %s command with id %i" % (name, self.command_event)
        event.post(event.Event(self.command_event, command=name))

    def translate_joy_button(self, evt):
        if not self.suppressed:
            button = evt.button
            config = self.get_configuration()
            code = self.command_event
            if button == config["joy-advance"]:
                self.post_command("advance")
            if button == config["joy-pause"]:
                self.post_command("pause")

    def translate_axis_motion(self, evt):
        if not self.suppressed:
            axis = evt.axis
            value = evt.value
            code = self.command_event
            if axis == 1:
                if value < 0:
                    self.post_command("up")
                elif value > 0:
                    self.post_command("down")
            else:
                if value > 0:
                    self.post_command("right")
                elif value < 0:
                    self.post_command("left")

    def is_command_active(self, command):
        if not self.suppressed:
            joystick = self.joystick
            if self.is_key_pressed(command):
                return True
            if command == "up":
                return joystick.is_direction_pressed(Joystick.up)
            elif command == "right":
                return joystick.is_direction_pressed(Joystick.right)
            elif command == "down":
                return joystick.is_direction_pressed(Joystick.down)
            elif command == "left":
                return joystick.is_direction_pressed(Joystick.left)
        else:
            return False

    def is_key_pressed(self, command):
        poll = keyboard.get_pressed()
        for key in self.key_map[command]:
            if poll[key]:
                return True

    def get_axes(self):
        axes = {}
        for direction in "up", "right", "down", "left":
            axes[direction] = self.is_command_active(direction)
        return axes


class Joystick:

    (up, right, down, left) = range(4)

    def __init__(self):
        js = None
        if joy.get_count() > 0:
            js = joy.Joystick(0)
            js.init()
        self.js = js

    def is_direction_pressed(self, direction):
        js = self.js
        if not js or direction > 4:
            return False
        if direction == 0:
            return js.get_axis(1) < 0
        elif direction == 1:
            return js.get_axis(0) > 0
        elif direction == 2:
            return js.get_axis(1) > 0
        elif direction == 3:
            return js.get_axis(0) < 0
from time import sleep

from pygame.locals import *

from esp_hadouken.pgfw.Configuration import TypeDeclarations
from esp_hadouken.pgfw.Game import Game
from esp_hadouken.Timer import Timer
from esp_hadouken.title.Title import Title
from esp_hadouken.overworld.Overworld import Overworld

class ESPHadouken(Game):

    def __init__(self):
        Game.__init__(self, type_declarations=Types())
        self.title.activate()
        # self.get_audio().mute()
        # self.subscribe(self.inform)

    def inform(self, event):
        print event

    def set_children(self):
        Game.set_children(self)
        self.timer = Timer(self)
        self.title = Title(self)
        self.overworld = Overworld(self)

    def update(self):
        self.title.update()
        self.overworld.update()


class Types(TypeDeclarations):

    additional_defaults = {

        "keys": {"list": ["up", "right", "down", "left"]},

        "title": {"int": ["prompt-size", "enemy-delay", "enemy-offset",
                          "toy-shift-delay", "turn-delay", "leave-delay",
                          "toy-turn-offset", "sky-arc-step",
                          "sky-arc-thickness", "sky-framerate",
                          "loop-delay"],

                  "float": "enemy-speed",

                  "list": "mask-vector-colors",

                  "int-list": ["wood-position", "toy-position", "toy-offset",
                               "enemy-enter-framerate", "background-framerate",
                               "sky-color", "sky-arc-color"]},

        "main-menu": {"int": ["frame-count", "framerate", "option-width",
                              "text-size"],

                      "int-list": ["size", "text-color",
                                   "background-color-range"],

                      "list": ["option-text", "select-fx"]},

        "toy": {"int": "framerate"},

        "overworld": {"int": ["toy-position", "wall-position", "dot-position"],

                      "int-list": ["wall-size", "wall-border"]},

        "dot": {"int": "frame-count",

                "int-list": ["framerate-range", "transparent-color"]},

        "engine": {"float": ["attack", "release", "deceleration",
                             "max-velocity", "initial-thrust",
                             "peak-acceleration", "peak-distance",
                             "min-negative-acceleration",
                             "min-negative-acceleration-distance",
                             "max-negative-acceleration", "calibrator-step"]},

        "sprite": {"list": ["dark-palette", "light-palette"]}}
216.73.216.78
216.73.216.78
216.73.216.78
 
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 😇