from os import mkdir, rename
from os.path import join, exists, dirname, basename
from time import strftime
from math import floor
from random import choice, random
from glob import glob

from pygame import Color, Rect, Surface
from pygame.font import Font
from pygame.image import load
from pygame.mixer import Sound
from pygame.event import clear
from pygame.locals import *

from _send.pgfw.GameChild import GameChild
from _send.pgfw.Animation import Animation
from _send.field.Field import Field
from _send.field.sideline.Sideline import Sideline
from _send.field.Charge import Charge
from _send.Send import SoundEffect

class Fields(Animation):

    def __init__(self, parent):
        Animation.__init__(self, parent)
        self.compare = self.get_delegate().compare
        self.load_configuration()
        self.subscribe(self.respond)
        self.set_sidelines()
        self.charge = Charge(self)
        self.life_meter = LifeMeter(self)
        self.score = Score(self)
        self.result = Result(self)
        music = self.music = []
        for path in sorted(glob(join(self.get_resource("fields", "music-path"),
                                     "[0-9]*"))):
            music.append(Sound(path))
        self.register(self.unsuppress_input)
        self.reset()
        self.read()

    def load_configuration(self):
        config = self.get_configuration("fields")
        self.palette_base = config["palette-base"]
        self.delimiter = config["delimiter"]
        self.fields_path = self.get_resource("fields", "path")
        self.backup_directory_name = self.\
                                     get_configuration("fields",
                                                       "backup-directory-name")

    def respond(self, event):
        if self.compare(event, "reset-game"):
            self.reset()
        elif self.compare(event, "raise-volume") or \
             self.compare(event, "lower-volume"):
            step = .1 * (-1 if event.command == "lower-volume" else 1)
            print step
            for sound in self.music:
                volume = sound.get_volume() + step
                print volume
                if volume < 0:
                    volume = 0
                elif volume > 1:
                    volume = 1
                sound.set_volume(volume)

    def reset(self):
        self.current_index = None
        for sound in self.music:
            sound.stop()
            sound.set_volume(self.get_configuration("fields",
                                                    "music-initial-volume"))
        self.music_index = None
        self.charge.reset()
        self.life_meter.reset()
        self.score.reset()
        self.result.reset()
        self.halt()
        self.suppressing_input = False
        self.loading = False

    def read(self, custom=False):
        path = self.custom_fields_path if custom else self.fields_path
        fields = self.fields = []
        index = {}
        for ii, line in enumerate(open(path)):
            name, parameters, background, foreground = \
                  map(str.strip, line.split(self.delimiter))
            ball, cup, speed, tartan_scale = parameters.split()
            background_color = self.parse_color(background)
            foreground_color = self.parse_color(foreground)
            fields.append(Field(self, name, float(ball), float(cup),
                                float(speed), float(tartan_scale),
                                background_color, foreground_color))
            index[name] = ii
        self.index = index

    def parse_color(self, color):
        return Color(*map(int, color.split(",")))

    def set_sidelines(self):
        self.sidelines = Sideline(self), Sideline(self, True)

    def get(self, name):
        return self.fields[self.get_index(name)]

    def get_index(self, name):
        return self.index[name]

    def get_current_field(self):
        if self.current_index is None:
            return
        return self.fields[self.current_index]

    def load(self, index=None, previous=False, suppress_title=False):
        if index is None:
            if not previous:
                index = self.get_next_index()
            else:
                index = self.get_previous_index()
        if not self.music[1].get_num_channels():
            self.music[1].play(-1)
        # if index / len(self.music) != self.music_index:
        #     if self.music_index is not None:
        #         self.music[self.music_index].fadeout(8000)
        #     self.music_index = index / len(self.music)
        #     self.music[self.music_index].play(-1, 0, 8000)
        current = self.get_current_field()
        if current:
            current.unload()
        self.fields[index].load(suppress_title)
        self.current_index = index
        for sideline in self.sidelines:
            sideline.refresh()
        self.charge.reset()
        self.loading = True

    def get_next_index(self):
        current = self.current_index
        if current is None:
            return 0
        if current == len(self.fields) - 1:
            return current
        return current + 1

    def get_previous_index(self):
        current = self.current_index
        if current is None or current == 0:
            return 0
        return current - 1

    def unsuppress_input(self):
        self.suppressing_input = False

    def write(self):
        fields_path = self.fields_path
        backup_directory_path = join(dirname(fields_path),
                                     self.backup_directory_name)
        if not exists(backup_directory_path):
            mkdir(backup_directory_path)
        rename(fields_path, join(backup_directory_path,
                                 "%s.%s" % (basename(fields_path),
                                            strftime("%Y%m%d%H%M%S"))))
        output = open(fields_path, "w")
        for field in self.fields:
            output.write("%s\n" % field)

    def update(self):
        current = self.get_current_field()
        if current:
            if self.suppressing_input and not self.is_playing(check_all=True):
                self.play(self.unsuppress_input, delay=500, play_once=True)
            current.update()
            for sideline in self.sidelines:
                sideline.update()
            self.charge.update()
            self.life_meter.update()
            self.score.update()
            self.result.update()
            if self.loading:
                self.loading = False
                self.suppressing_input = True
                clear()
        Animation.update(self)


class LifeMeter(GameChild, Rect):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.display_surface = self.get_display_surface()
        self.heart = load(self.get_resource("life-meter", "heart-path")).\
                     convert()
        self.miss = load(self.get_resource("life-meter", "miss-path")).\
                    convert()
        self.initial_lives = self.get_configuration("life-meter",
                                                    "initial-lives")
        self.max_lives = self.get_configuration("life-meter", "max-lives")
        Rect.__init__(self, 0, 0, self.heart.get_width() * self.max_lives,
                      self.heart.get_height())
        self.center = parent.sidelines[1].center
        self.reset()

    def reset(self):
        self.lives = self.initial_lives

    def remove_life(self):
        self.lives -= 1

    def add_life(self):
        if self.lives < self.max_lives:
            self.lives += 1

    def update(self):
        for ii, x in enumerate(xrange(0, self.w, self.w / self.max_lives)):
            image = self.heart if ii < self.lives else self.miss
            self.display_surface.blit(image, self.move(x, 0))


class Score(GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.display_surface = self.get_display_surface()
        font = self.font = Font(self.get_resource("display", "font-path"), 24)
        self.high_score = 0
        path = self.get_resource("score", "path")
        if path is not None:
            for line in open(path):
                if int(line) > self.high_score:
                    self.high_score = int(line)
        self.set_high_score_surface()
        self.reset()

    def set_high_score_surface(self):
        font = Font(self.get_resource("display", "font-path"), 10)
        top = font.render("best", True, (221, 172, 227), (255, 255, 255))
        bottom = font.render(str(self.high_score), True, (170, 132, 208),
                             (255, 255, 255))
        tr, br = top.get_rect(), bottom.get_rect()
        surface = self.high_score_surface = Surface((max(tr.w, br.w) + 4,
                                                     tr.h + br.h))
        surface.fill((255, 255, 255))
        rect = self.high_score_rect = surface.get_rect()
        tr.midtop = rect.midtop
        surface.blit(top, tr)
        br.midbottom = rect.midbottom
        surface.blit(bottom, br)
        rect.bottomright = self.display_surface.get_rect().bottomright

    def reset(self):
        self.score = 0
        self.set_surface()

    def increase(self, amount):
        self.score += amount
        self.set_surface()
        if self.score > self.high_score:
            self.high_score = self.score
            self.set_high_score_surface()

    def set_surface(self):
        text = str(self.score)
        font = self.font
        width, height = font.size(text)
        text_surface = Surface((width + 4, height), SRCALPHA)
        text_surface.blit(font.render(text, True, (255, 255, 0)), (0, 0))
        text_surface.blit(font.render(text, True, (0, 255, 0)), (4, 0))
        background = (255, 255, 255)
        text_surface.blit(font.render(text, True, (0, 0, 255)), (2, 0))
        text_rect = text_surface.get_rect()
        surface = self.surface = Surface(text_rect.inflate(12, 2).size,
                                         SRCALPHA)
        surface.fill(background)
        rect = self.rect = surface.get_rect()
        text_rect.center = rect.center
        rect.center = self.parent.sidelines[0].center
        surface.blit(text_surface, text_rect)

    def update(self):
        self.display_surface.blit(self.surface, self.rect)
        self.display_surface.blit(self.high_score_surface, self.high_score_rect)


class Result(Animation):

    def __init__(self, parent):
        Animation.__init__(self, parent, self.render)
        self.register(self.render,
                      self.get_configuration("result", "framerate"))
        self.delegate = self.get_game().delegate
        self.display_surface = self.get_display_surface()
        self.subscribe(self.respond)
        config = self.get_configuration("result")
        regions = self.regions = config["text"]
        portholes = self.portholes = {}
        for path in glob(join(self.get_resource("result", "porthole-path"),
                              "*")):
            portholes[basename(path).split(".")[0].upper()] = load(path).\
                                                              convert_alpha()
        self.font = Font(self.get_resource("display", "font-path"),
                         config["font-size"])
        self.main_color_probability = config["main-color-probability"]
        text_colors = self.text_colors = {}
        for ii, color in enumerate(config["colors"]):
            text_colors[regions[ii]] = Color(color + "FF")
        self.success_audio = SoundEffect(self.get_resource("result",
                                                           "success-audio"), .2)
        self.miss_audio = SoundEffect(self.get_resource("result", "miss-audio"),
                                      1.0)
        self.next_level_audio = SoundEffect(self.\
                                            get_resource("result",
                                                         "next-level-audio"),
                                            .1)
        self.reset()

    def respond(self, event):
        if self.is_playing() and self.delegate.compare(event, "any"):
            if self.success:
                self.parent.load()
                self.next_level_audio.play()
            else:
                if self.parent.life_meter.lives > 0:
                    self.parent.load(self.parent.current_index,
                                     suppress_title=True)
                else:
                    path = self.get_resource("score", "path")
                    if path is None:
                        path = join(\
                            self.get_configuration("setup",
                                                   "resource-search-path")[0],
                            self.get_configuration("score", "path"))
                    open(path, "a").write(str(self.parent.score.score) + "\n")
                    self.parent.score.reset()
                    self.parent.life_meter.reset()
                    self.parent.load(0)
            self.reset()

    def reset(self):
        self.halt()

    def render(self):
        font = self.font
        region = self.regions[self.region_index]
        color = self.text_colors[region]
        if self.region_index > 0 and random() > self.main_color_probability:
            colors = self.text_colors.copy()
            colors.pop(self.regions[0])
            colors.pop(region)
            color = choice(colors.values())
        text = font.render(region, True, color, (255, 255, 255))
        tr = text.get_rect()
        surface = self.text_surface = Surface((tr.w + 50, tr.h + 10), SRCALPHA)
        surface.fill((255, 255, 255))
        rect = self.text_rect = surface.get_rect()
        tr.center = rect.center
        surface.blit(text, tr)
        rect.center = self.display_surface.get_rect().center

    def evaluate(self):
        field = self.parent.get_current_field()
        ball, cup = field.ball, field.cup
        if not ball.rect.colliderect(cup.location):
            self.parent.life_meter.remove_life()
            self.set_region(0)
            self.success = False
            if self.parent.life_meter.lives > 0:
                self.miss_audio.play()
            else:
                self.miss_audio.play(-1)
                self.miss_audio.fadeout(2600)
        else:
            distance = max(abs(ball.location.centerx - cup.location.centerx),
                           abs(ball.location.centery - cup.location.centery))
            ratio = 1 - float(distance) / (cup.location.w / 2 + \
                                           ball.location.w / 2 + 1)
            index = int(floor(len(self.regions[1:]) * ratio))
            self.parent.score.increase((self.parent.current_index + 1) * \
                                       (index + 1))
            self.set_region(index + 1)
            self.success = True
            self.success_audio.play()
            fields = self.parent
            level_index = fields.current_index
            if level_index != len(fields.index) - 1 and level_index % 5 == 4:
                fields.life_meter.add_life()
        self.play()

    def set_region(self, index):
        self.region_index = index
        surface = self.porthole_surface = self.portholes[self.regions[\
            self.region_index]]
        rect = self.porthole_rect = surface.get_rect()
        rect.center = self.display_surface.get_rect().center

    def update(self):
        if self.is_playing():
            Animation.update(self)
            self.display_surface.blit(self.porthole_surface, self.porthole_rect)
            self.display_surface.blit(self.text_surface, self.text_rect)
34.204.174.110
34.204.174.110
34.204.174.110
 
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 😇