from collections import deque
from math import ceil

from pygame import Surface
from pygame.draw import polygon
from pygame.locals import *

from _send.pgfw.Sprite import Sprite

class Arrow(Sprite):

    LEFT, RIGHT = (-1, 1)

    def __init__(self, parent, size, hue, saturation, overlap, count,
                 orientation):
        Sprite.__init__(self, parent)
        self.load_configuration()
        self.size = size
        self.hue = hue
        self.saturation = saturation
        self.overlap = overlap
        self.count = count
        self.orientation = orientation
        self.set_mask()
        self.set_hues()
        self.set_frames()

    def load_configuration(self):
        config = self.get_configuration("arrow")
        self.frame_count = config["frame-count"]

    def set_mask(self):
        surface = Surface(self.get_size())
        surface.set_colorkey((0, 0, 0))
        rect = surface.get_rect()
        width = self.size[0]
        x = 0
        for ii in xrange(self.count):
            if self.orientation == self.LEFT:
                points = (x, rect.centery), (x + width, 0),\
                         (x + width, rect.bottom)
            else:
                points = (x, 0), (x + width, rect.centery), (x, rect.bottom)
            polygon(surface, (255, 255, 255), points)
            x += width - self.overlap
        self.mask = surface

    def get_size(self):
        count = self.count
        return self.size[0] * count - self.overlap * (count - 1), self.size[1]

    def set_hues(self):
        start, end = self.hue
        step = float(end - start) / (self.frame_count - 1)
        hues = deque([start])
        while start < end:
            start += step
            hues.append(start)
        hues.append(end)
        self.hues = hues

    def set_frames(self):
        for _ in xrange(self.frame_count):
            self.append_frame()

    def append_frame(self):
        width, height = self.get_size()
        gradient = Surface((width, height))
        gradient.set_colorkey((0, 0, 0))
        hues = self.hues
        step = float(width) / self.count / len(hues)
        x = 0
        color = Color(0, 0, 0)
        while x < width:
            for hue in hues:
                color.hsla = hue, self.saturation, 50, 100
                gradient.fill(color, (int(x), 0, ceil(step), height))
                x += step
        hues.rotate(self.orientation)
        mask = self.mask.convert()
        gradient.blit(mask, (0, 0), None, BLEND_RGBA_MIN)
        self.add_frame(gradient)
from pygame.key import get_mods
from pygame.locals import *

from _send.pgfw.GameChild import GameChild

class Editor(GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.fields = self.get_game().fields
        self.subscribe(self.respond_to_key, KEYDOWN)

    def respond_to_key(self, event):
        key = event.key
        fields = self.fields
        field = fields.get_current_field()
        mods = get_mods()
        step = self.get_step(mods)
        if key == K_h:
            self.adjust_color(field, (step, 0, 0), mods)
        elif key == K_s:
            self.adjust_color(field, (0, step, 0), mods)
        elif key == K_l:
            self.adjust_color(field, (0, 0, step), mods)
        elif key == K_BACKQUOTE:
            pass
        elif key == K_EQUALS:
            fields.write()
        elif key == K_b:
            pass
        elif key == K_c:
            pass
        elif key == K_t:
            pass
        elif key == K_RIGHTBRACKET:
            fields.load()
        elif key == K_LEFTBRACKET:
            fields.load(previous=True)
        elif key == K_w:
            fields.write()

    def get_step(self, mods):
        sign = -1 if self.alt_pressed(mods) else 1
        return 1 * sign if self.ctrl_pressed(mods) else 10 * sign

    def alt_pressed(self, mods):
        return mods & KMOD_ALT

    def ctrl_pressed(self, mods):
        return mods & KMOD_CTRL

    def adjust_color(self, field, channels, mods):
        if self.shift_pressed(mods):
            field.adjust_color(field.foreground_id, *channels)
        else:
            field.adjust_color(field.background_id, *channels)

    def shift_pressed(self, mods):
        return mods & KMOD_SHIFT
from pygame import Surface, Color
from pygame.font import Font
from pygame.locals import *

from _send.pgfw.Animation import Animation
from _send.pgfw.Sprite import Sprite
from _send.field.ball.Ball import Ball
from _send.field.Cup import Cup

class Field(Animation):

    background_id, foreground_id = 0, 1

    def __init__(self, parent, name, ball_scale, cup_scale, speed,
                 tartan_scale, background_color, foreground_color):
        Animation.__init__(self, parent)
        self.name = name
        self.ball_scale = ball_scale
        self.cup_scale = cup_scale
        self.speed = speed
        self.tartan_scale = tartan_scale
        self.colors = background_color, foreground_color
        self.title = Title(self)
        self.register(self.deactivate_title)

    def load(self, suppress_title=False):
        self.halt()
        if not suppress_title:
            self.title.unhide()
            self.play(self.deactivate_title, delay=5000)
        self.display_surface = self.get_display_surface()
        self.set_background()
        self.set_ball()
        self.set_cup()

    def deactivate_title(self):
        self.title.hide()

    def set_background(self):
        self.background = Surface(self.display_surface.get_size())
        self.paint_background()

    def paint_background(self):
        self.background.fill(self.get_background_color())

    def get_background_color(self):
        return self.colors[self.background_id]

    def set_ball(self):
        self.ball = Ball(self)

    def set_cup(self):
        self.cup = Cup(self)

    def __str__(self):
        br, bg, bb, ba = self.get_background_color()
        fr, fg, fb, fa = self.get_foreground_color()
        return "%s | %.3f %.3f %.3f %.3f | %i, %i, %i | %i, %i, %i" % \
               (self.name, self.ball_scale, self.cup_scale, self.speed,
                self.tartan_scale, br, bg, bb, fr, fg, fb)

    def get_foreground_color(self):
        return self.colors[self.foreground_id]

    def adjust_color(self, index, dh, ds, dl):
        colors = self.colors
        hue, saturation, lightness, alpha = colors[index].hsla
        hue, saturation, lightness = hue + dh, saturation + ds, lightness + dl
        constrain = self.constrain_channel
        hue = constrain(hue, 360)
        saturation = constrain(saturation, 100)
        lightness = constrain(lightness, 100)
        colors[index].hsla = hue, saturation, lightness, alpha
        self.paint_background()
        self.ball.set_color()
        self.cup.set_color()

    def constrain_channel(self, channel, limit):
        if channel < 0:
            channel = 0
        elif channel > limit:
            channel = limit
        return channel

    def unload(self):
        del self.display_surface
        del self.ball
        del self.cup
        del self.background

    def update(self):
        Animation.update(self)
        self.clear()
        self.title.update()
        self.cup.update()
        self.ball.update()

    def clear(self, rect=None):
        if rect is None:
            rect = self.background.get_rect()
        self.display_surface.blit(self.background, rect)


class Title(Sprite):

    def __init__(self, parent):
        Sprite.__init__(self, parent)
        color = Color(0, 0, 0)
        font = Font(self.get_resource("display", "font-path"), 14)
        font.set_bold(True)
        font.set_italic(True)
        name = parent.name.upper()
        shadow = font.render(name, True, parent.get_background_color())
        mask = font.render(name, True, parent.get_foreground_color())
        base = Surface((shadow.get_width() + 5, shadow.get_height() + 1),
                       SRCALPHA)
        for ii, lightness in enumerate(xrange(0, 100, 5)):
            color.hsla = 60, 100, lightness, 100
            frame = base.copy()
            for x in xrange(0, frame.get_width(), 2):
                frame.set_at((x, frame.get_height() - 1),
                             self.get_dot_color(x, ii))
            for y in xrange(0, frame.get_height(), 2):
                frame.set_at((frame.get_width() - 1, y),
                             self.get_dot_color(y, ii))
            frame.blit(shadow, (0, 0))
            frame.blit(mask, (2, 0))
            text = font.render(name, True, color)
            frame.blit(text, (4, 0))
            self.add_frame(frame)
        self.location.topleft = parent.parent.sidelines[0].bottomleft

    def get_dot_color(self, a, b):
        return Color(*((0, 0, 0), (255, 255, 255))[((a / 2) % 2 + (b % 2)) % 2])
216.73.216.55
216.73.216.55
216.73.216.55
 
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 😇