from pygame import display
from pygame.font import Font
from pygame.time import get_ticks, wait

from GameChild import GameChild

class Mainloop(GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.overflow = 0
        self.frame_count = 1
        self.actual_frame_duration = 0
        self.frames_this_second = 0
        self.last_framerate_display = 0
        self.load_configuration()
        self.init_framerate_display()
        self.last_ticks = get_ticks()
        self.stopping = False

    def load_configuration(self):
        config = self.get_configuration("display")
        self.target_frame_duration = config["frame-duration"]
        self.wait_duration = config["wait-duration"]
        self.skip_frames = config["skip-frames"]
        self.show_framerate = config["show-framerate"]
        self.framerate_text_size = config["framerate-text-size"]
        self.framerate_text_color = config["framerate-text-color"]
        self.framerate_text_background = config["framerate-text-background"]
        self.framerate_display_flag = config["framerate-display-flag"]

    def init_framerate_display(self):
        if self.framerate_display_active():
            screen = self.get_screen()
            self.last_framerate_count = 0
            self.framerate_topright = screen.get_rect().topright
            self.display_surface = screen
            self.font = Font(None, self.framerate_text_size)
            self.font.set_bold(True)
            self.render_framerate()

    def framerate_display_active(self):
        return self.check_command_line(self.framerate_display_flag) or \
               self.show_framerate

    def render_framerate(self):
        text = self.font.render(str(self.last_framerate_count), False,
                                self.framerate_text_color,
                                self.framerate_text_background)
        rect = text.get_rect()
        rect.topright = self.framerate_topright
        self.framerate_text = text
        self.framerate_text_rect = rect

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

    def advance_frame(self):
        refresh = False
        while self.frame_count > 0:
            refresh = True
            self.parent.frame()
            if self.framerate_display_active():
                self.update_framerate()
            self.frame_count -= 1
            if not self.skip_frames:
                break
        if refresh:
            display.update()

    def update_frame_duration(self):
        last_ticks = self.last_ticks
        actual_frame_duration = get_ticks() - last_ticks
        last_ticks = get_ticks()
        while actual_frame_duration < self.target_frame_duration:
            wait(self.wait_duration)
            actual_frame_duration += get_ticks() - last_ticks
            last_ticks = get_ticks()
        self.actual_frame_duration = actual_frame_duration
        self.last_ticks = last_ticks

    def update_overflow(self):
        self.frame_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.frame_count += 1
            overflow -= target_frame_duration
        overflow = self.overflow

    def update_framerate(self):
        count = self.frames_this_second + 1
        if get_ticks() - self.last_framerate_display > 1000:
            if count != self.last_framerate_count:
                self.last_framerate_count = count
                self.render_framerate()
            self.last_framerate_display = get_ticks()
            count = 0
        self.display_surface.blit(self.framerate_text, self.framerate_text_rect)
        self.frames_this_second = count

    def stop(self):
        self.stopping = True
from os import makedirs
from os.path import exists, join
from sys import exc_info
from time import strftime

from pygame import image

from GameChild import *
from Input import *

class ScreenGrabber(GameChild):

    def __init__(self, game):
        GameChild.__init__(self, game)
        self.delegate = self.get_delegate()
        self.load_configuration()
        self.subscribe(self.save_display)

    def load_configuration(self):
        config = self.get_configuration("screen-captures")
        self.save_path = config["path"]
        self.file_name_format = config["file-name-format"]
        self.file_extension = config["file-extension"]

    def save_display(self, event):
        if self.delegate.compare(event, "capture-screen"):
            directory = self.save_path
            try:
                if not exists(directory):
                    makedirs(directory)
                name = self.build_name()
                path = join(directory, name)
                capture = image.save(self.get_screen(), path)
                self.print_debug("Saved screen capture to %s" % (path))
            except:
                self.print_debug("Couldn't save screen capture to %s, %s" %\
                                 (directory, exc_info()[1]))

    def build_name(self):
        return "{0}.{1}".format(strftime(self.file_name_format),
                                self.file_extension)
from os import walk, remove
from os.path import sep, join, exists, normpath
from re import findall, sub
from distutils.core import setup
from distutils.command.install import install
from pprint import pprint
from fileinput import FileInput
from re import sub, match

from Configuration import *

class Setup:

    config = Configuration()
    manifest_path = "MANIFEST"

    def __init__(self):
        pass

    def remove_old_mainfest(self):
        path = self.manifest_path
        if exists(path):
            remove(path)

    def build_package_list(self):
        packages = []
        config = self.config.get_section("setup")
        locations = [config["package-root"]] + config["additional-packages"]
        for location in locations:
            if exists(location):
                for root, dirs, files in walk(location, followlinks=True):
                    packages.append(root.replace(sep, "."))
        return packages

    def build_data_map(self):
        include = []
        config = self.config.get_section("setup")
        exclude = map(normpath, config["data-exclude"])
        for root, dirs, files in walk("."):
            dirs = self.remove_excluded(dirs, root, exclude)
            files = [join(root, f) for f in self.remove_excluded(files, root,
                                                                 exclude)]
            if files:
                include.append((normpath(join(config["installation-path"],
                                              root)), files))
        return include

    def remove_excluded(self, paths, root, exclude):
        removal = []
        for path in paths:
            if normpath(join(root, path)) in exclude:
                removal.append(path)
        for path in removal:
            paths.remove(path)
        return paths

    def translate_title(self):
        config = self.config.get_section("setup")
        title = config["title"].replace(" ", config["whitespace-placeholder"])
        return sub("[^\w-]", config["special-char-placeholder"], title)

    def build_description(self):
        description = ""
        path = self.config.get("setup", "description-file")
        if exists(path):
            description = "\n%s\n%s\n%s" % (file(path).read(),
                                            "Changelog\n=========",
                                            self.translate_changelog())
        return description

    def translate_changelog(self):
        translation = ""
        path = self.config.get("setup", "changelog")
        if exists(path):
            lines = file(path).readlines()
            package_name = lines[0].split()[0]
            for line in lines:
                line = line.strip()
                if line.startswith(package_name):
                    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

    def setup(self, windows=[], options={}):
	print "running setup..."
        self.remove_old_mainfest()
        config = self.config.get_section("setup")
	scripts = []
	if config["init-script"]:
	    scripts.append(config["init-script"])
        setup(cmdclass={"install": insert_resource_path},
              name=self.translate_title(),
              packages=self.build_package_list(),
              scripts=scripts,
              data_files=self.build_data_map(),
              requires=config["requirements"],
              version=config["version"],
              description=config["summary"],
              classifiers=config["classifiers"],
              long_description=self.build_description(),
              license=config["license"],
              platforms=config["platforms"],
              author=config["contact-name"],
              author_email=config["contact-email"],
              url=config["url"],
	      windows=windows,
	      options=options)


class insert_resource_path(install):

    def run(self):
        install.run(self)
        self.edit_game_object_file()

    def edit_game_object_file(self):
        config = Configuration().get_section("setup")
        for path in self.get_outputs():
            if path.endswith(config["main-object"]):
                for line in FileInput(path, inplace=True):
                    pattern = "^ *{0} *=.*".\
                              format(config["resource-path-identifier"])
                    if match(pattern, line):
                        line = sub("=.*$", "= \"{0}\"".\
                                   format(config["installation-path"]), line)
                    print line.strip("\n")
44.200.117.166
44.200.117.166
44.200.117.166
 
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 😇