from os import environ

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

from GameChild import *

class Display(GameChild):

    def __init__(self, game):
        GameChild.__init__(self, game)
        self.delegate = self.get_delegate()
        self.load_configuration()
        self.align_window()
        self.init_screen()
        self.set_caption()
        self.set_icon()
        self.set_mouse_visibility()
        self.subscribe(self.toggle_fullscreen)

    def load_configuration(self):
        config = self.get_configuration("display")
        self.centered = config["centered"]
        self.fullscreen_enabled = config["fullscreen"]
        self.caption = config["caption"]
        self.windowed_flag = config["windowed-flag"]
        self.icon_path = self.get_resource("display", "icon-path")
        self.mouse_visibility = self.get_configuration("mouse", "visible")

    def align_window(self):
        if self.centered:
            environ["SDL_VIDEO_CENTERED"] = "1"

    def init_screen(self):
        flags = 0
        if self.fullscreen_requested():
            flags = FULLSCREEN
        self.set_screen(flags)

    def fullscreen_requested(self):
        return not self.check_command_line(self.windowed_flag) and \
               self.fullscreen_enabled

    def set_screen(self, flags=0, dimensions=None):
        self.dimensions_changed = dimensions is not None
        if dimensions is None:
            if display.get_surface():
                dimensions = display.get_surface().get_size()
            else:
                dimensions = self.get_configuration("display", "dimensions")
        self.screen = display.set_mode(dimensions, flags)
        if self.dimensions_changed:
            interpolator = self.get_game().interpolator
            if interpolator.gui_enabled:
                interpolator.gui.rearrange()

    def set_caption(self):
        display.set_caption(self.caption)

    def set_icon(self):
        if self.icon_path:
            print self.icon_path
            display.set_icon(image.load(self.icon_path).convert_alpha())

    def set_mouse_visibility(self, visibility=None):
        if visibility is None:
            visibility = self.mouse_visibility
        return mouse.set_visible(visibility)

    def get_screen(self):
        return self.screen

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

    def toggle_fullscreen(self, event):
        if self.delegate.compare(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, time
from pygame.locals import *

import Game

class GameChild:

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

    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, linebreaks=True):
        config = self.game.configuration
        if option is None and section is None:
            return config
        if option and section:
            rvalue = config.get(section, option)
            if not linebreaks and isinstance(rvalue, str):
                rvalue = rvalue.replace("\n", " ")
            return rvalue
        return config.get_section(section)

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

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

    def get_display_surface(self):
        current = self
        attribute = "display_surface"
        while not isinstance(current, Game.Game):
            if hasattr(current, attribute):
                return getattr(current, attribute)
            current = current.parent
        return current.display.get_screen()

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

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

    def get_resource(self, path_or_section, option=None):
        config = self.get_configuration()
        rel_path = path_or_section
        if option is not None:
            rel_path = config.get(path_or_section, option)
        if rel_path:
            for root in config.get("setup", "resource-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(path_or_section, option))

    def is_shared_mode(self):
        return self.check_command_line("s")

    def check_command_line(self, flag):
        return "-" + flag in argv

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

    def is_debug_mode(self):
        return self.check_command_line("d")

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

    def subscribe(self, callback, kind=None):
        self.game.delegate.add_subscriber(callback, kind)

    def unsubscribe(self, callback, kind=None):
        self.game.delegate.remove_subscriber(callback, kind)
import cProfile
from time import strftime
from os import mkdir
from os.path import join, exists

from GameChild import GameChild

class Profile(cProfile.Profile, GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        cProfile.Profile.__init__(self)
        if self.requested():
            self.enable()

    def requested(self):
        return self.check_command_line("p")

    def end(self):
        if self.requested():
            root = "stat/"
            if not exists(root):
                mkdir(root)
            self.disable()
            self.create_stats()
            self.dump_stats(join(root, strftime("%Y%m%d-%H%M_%S.stat")))
18.232.179.37
18.232.179.37
18.232.179.37
 
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 😇