from pygame import Surface, Color, Rect
from pygame.time import get_ticks

from ball_cup.pgfw.Animation import Animation

class Charge(Animation, Surface):

    def __init__(self, parent):
        Animation.__init__(self, parent, self.flash)
        self.display_surface = self.get_display_surface()
        self.input = self.get_input()
        self.load_configuration()
        self.register(self.flash, interval=self.interval)
        self.init_surface()
        self.reset()
        self.play()

    def load_configuration(self):
        config = self.get_configuration("charge")
        self.transparent_color = config["transparent-color"]
        self.peak_time = config["peak-time"]
        self.colors = self.build_color_list(config["colors"])
        self.width = config["width"]
        self.interval = config["interval"]
        self.magnitude_range = config["magnitude-range"]

    def build_color_list(self, colors):
        return [Color(color + "FF") for color in colors]

    def init_surface(self):
        Surface.__init__(self, (self.width, self.magnitude_range[1] * 2))
        self.set_colorkey(self.transparent_color)
        self.fill(self.transparent_color)
        rect = self.get_rect()
        rect.centery = self.display_surface.get_rect().centery
        self.rect = rect

    def reset(self):
        self.cancel()
        self.set_strength()
        self.color_index = 0

    def cancel(self):
        self.start = None
        self.fill(self.transparent_color)

    def set_strength(self):
        strength = 0
        if self.start:
            peak = self.peak_time
            elapsed = (get_ticks() - self.start) % peak
            strength = min(1, float(elapsed) / peak)
        self.strength = strength

    def is_charging(self):
        return self.start is not None

    def flash(self):
        if self.is_charging():
            self.increment_color_index()
            self.fill(self.transparent_color)
            self.fill(self.colors[self.color_index], self.get_fill_section())

    def get_fill_section(self):
        lower, upper = self.magnitude_range
        magnitude = self.strength * (upper - lower) + lower
        rect = Rect(0, 0, self.get_width(), magnitude * 2)
        rect.top = self.get_height() / 2 - magnitude
        return rect

    def increment_color_index(self):
        index = self.color_index + 1
        if index >= len(self.colors):
            index = 0
        self.color_index = index

    def update(self):
        self.check_input()
        self.set_strength()
        self.clear()
        Animation.update(self)
        self.draw()

    def check_input(self):
        pressed = self.input.is_command_active("left")
        charging = self.is_charging()
        if not pressed:
            if charging:
                self.release()
        elif pressed and not charging:
            self.hold()

    def release(self):
        self.parent.send()
        self.cancel()

    def hold(self):
        self.start = get_ticks()

    def clear(self):
        self.parent.parent.clear(self.rect)

    def draw(self):
        self.display_surface.blit(self, self.rect)
from ball_cup.pgfw.GameChild import GameChild
from ball_cup.field.scoreboard.Score import Score

class Scoreboard(GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.display_surface = self.get_display_surface()
        self.load_configuration()
        self.set_scores()
        self.reset()

    def load_configuration(self):
        config = self.get_configuration("scoreboard")
        self.height = config["height"]
        self.segment_width = config["score-segment-width"]
        self.margin_top = config["margin-top"]
        self.border_width = config["score-border-width"]
        self.border_color = config["score-border-color"]

    def set_scores(self):
        display_surface = self.get_display_surface()
        height = self.height
        segment_width = self.segment_width
        colors = self.parent.result.success_colors
        border_width = self.border_width
        border_color = self.border_color
        centerx = display_surface.get_rect().centerx
        margin = self.margin_top
        self.scores = [Score(self, display_surface, height, segment_width,
                             colors, border_width, border_color, centerx,
                             margin),
                       Score(self, display_surface, height, segment_width,
                             colors, border_width, border_color, centerx,
                             display_surface.get_height() - height - margin)]

    def reset(self):
        for score in self.scores:
            score.reset()

    def refresh(self):
        for score in self.scores:
            score.insert(self.parent.result.color)

    def update(self):
        for score in self.scores:
            score.draw()

    def clear(self):
        for score in self.scores:
            self.parent.clear(score.rect)
from pygame import Surface

from ball_cup.pgfw.GameChild import GameChild

class Score(Surface, GameChild):

    def __init__(self, parent, display_surface, height, segment_width, colors,
                 border_width, border_color, centerx, top):
        GameChild.__init__(self, parent)
        self.display_surface = display_surface
        self.height = height
        self.segment_width = segment_width
        self.colors = colors
        self.border_width = border_width
        self.border_color = border_color
        self.centerx = centerx
        self.top = top
        self.reset()
        self.populate()

    def reset(self):
        counts = []
        for color in self.colors:
            counts.append([color, 0])
        self.draw_counts = counts
        self.populate()

    def populate(self):
        self.init_surface()
        self.fill_borders()
        self.fill_center()

    def init_surface(self):
        Surface.__init__(self, (self.measure_length(),
                                self.height + self.border_width * 2))
        rect = self.get_rect()
        rect.centerx = self.centerx
        rect.top = self.top
        self.rect = rect

    def measure_length(self):
        length = 0
        for color, count in self.draw_counts:
            length += count * self.segment_width
        return length + self.border_width * 2

    def fill_borders(self):
        color = self.border_color
        rect = self.rect
        thickness = self.border_width
        self.fill(color, (0, 0, rect.w, thickness))
        self.fill(color, (rect.w - thickness, 0, thickness, rect.h))
        self.fill(color, (0, rect.h - thickness, rect.w, thickness))
        self.fill(color, (0, 0, thickness, rect.h))

    def fill_center(self):
        offset = self.border_width
        size = self.segment_width / 2, self.get_height() - offset * 2
        right = self.rect.w
        indent = offset
        for color in self.colors:
            for _ in range(self.get_draw_count(color)):
                self.fill(color, ((indent, offset), size))
                self.fill(color, ((right - indent - size[0], offset), size))
                indent += size[0]

    def get_draw_count(self, key):
        for color, count in self.draw_counts:
            if key == color:
                return count

    def insert(self, color):
        counts = self.draw_counts
        for ii in range(len(counts)):
            if counts[ii][0] == color:
                counts[ii][1] += 1
        self.populate()

    def draw(self):
        self.display_surface.blit(self, self.rect)
216.73.216.163
216.73.216.163
216.73.216.163
 
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 😇