#!/usr/bin/env python

from random import randint, random, choice, randrange, uniform
from math import sin, tan, radians, copysign, degrees, cos, asin
from os import mkdir, remove
from os.path import join, exists
from sys import argv
from glob import glob
from collections import deque
from itertools import chain

from pygame.locals import *
from pygame import Surface, Color, PixelArray
from pygame.font import Font
from pygame.mixer import Sound, Channel, get_num_channels
from pygame.draw import polygon, line, circle, aaline
from pygame.gfxdraw import aapolygon, aacircle, filled_circle
from pygame.image import load, save
from pygame.transform import rotate, smoothscale, rotozoom, scale, flip
from pygame.event import clear
from pygame.display import set_mode

from lib.pgfw.pgfw.Game import Game
from lib.pgfw.pgfw.GameChild import GameChild
from lib.pgfw.pgfw.Sprite import Sprite
from lib.pgfw.pgfw.Animation import Animation
from lib.pgfw.pgfw.Vector import Vector
from lib.pgfw.pgfw.extension import (get_distance, get_delta, place_in_rect,
                                     get_step, collide_line_with_rect)

class SoundEffect(GameChild, Sound):

    def __init__(self, parent, path, volume=1.0):
        GameChild.__init__(self, parent)
        Sound.__init__(self, path)
        self.display_surface = self.get_display_surface()
        self.set_volume(volume)

    def play(self, loops=0, maxtime=0, fade_ms=0, position=None, x=None):
        channel = Sound.play(self, loops, maxtime, fade_ms)
        if x is not None:
            position = float(x) / self.display_surface.get_width()
	if position is not None and channel is not None:
            channel.set_volume(*self.get_panning(position))
        return channel

    def get_panning(self, position):
        return 1 - max(0, ((position - .5) * 2)), \
               1 + min(0, ((position - .5) * 2))

# ===--------------------===
# )))) FISSION / FUSION ((((
# ===--------------------===

class iQue(Game, Sprite):

    GENERATE_FLAG = "-generate"
    FRAME_DIR = "frame/"

    def __init__(self):
        Game.__init__(self)
        Sprite.__init__(self, self, 1000)
        if self.check_command_line(self.GENERATE_FLAG):
            pixels = PixelArray(smoothscale(\
                load(self.get_resource("Untitled.png")).convert(), (500, 400)))
            if not exists(self.FRAME_DIR):
                mkdir(self.FRAME_DIR)
            for path in glob("%s/*.png" % self.FRAME_DIR):
                remove(path)
            for ii in xrange(int(argv[argv.index("-" + \
                                                 self.GENERATE_FLAG) + 1])):
                color = Color(0, 0, 0)
                for x in xrange(len(pixels)):
                    for y in xrange(len(pixels[0])):
                        h, s, l, a = Color(*Surface((0, 0)).\
                                           unmap_rgb(pixels[x][y])).hsla
                        color.hsla = int((h + (ii % 240)) % 360), int(s), 50,\
                                     100
                        pixels[x][y] = color
                        pixels[x - 138][y - (ii % 1024)] = pixels[\
                            x - (ii % 128)][y - (ii % 2)]
                print ii
                save(pixels.make_surface(), "%s/%04i.png" % (self.FRAME_DIR,
                                                             ii))
        for path in sorted(glob("%s/*.png" % self.FRAME_DIR)):
            self.add_frame(load(path).convert())
        self.location.topleft = -10, -10
        self.goal = Goal(self)
        self.calorie = Calorie(self)
        self.carrot = Carrot(self)
        self.subscribe(self.respond)
        self.reset()
        clear()

    def respond(self, event):
        if self.delegate.compare(event, "reset-game"):
            self.reset()

    def reset(self):
        self.calorie.reset()

    def update(self):
        Sprite.update(self)
        self.goal.update()
        self.carrot.update()
        self.calorie.update()


class Carrot(Sprite):

    SIZE = 60, 35
    MARGIN = 30

    def __init__(self, parent):
        Sprite.__init__(self, parent)
        self.add_frame(smoothscale(load("Emparchment.png").convert_alpha(),
                                   self.SIZE))
        self.spawn()

    def spawn(self):
        place_in_rect(self.get_display_surface().get_rect(), self.location,
                      True, self.parent.goal.skull.location.inflate(\
                          [self.MARGIN] * 2))
        self.parent.calorie.find_carrot()


class Goal(GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.skull = Skull(self)
        self.shield = Shield(self)

    def update(self):
        self.skull.update()


class Skull(Sprite):

    MARGIN = 10

    def __init__(self, parent):
        Sprite.__init__(self, parent)
        self.add_frame(load("Pencil.png").convert_alpha())
        self.location.bottomright = self.get_display_surface().get_rect().\
                                    move([-self.MARGIN] * 2).bottomright


class Shield(GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)


class Calorie(Sprite):

    SIZE = 71, 88
    SPAWN_MARGIN = 30
    FETCH_DELAY = 1000
    SPEED = 7
    CARROT_BOX_SHRINK = -20, -10
    PROJECTION_LENGTH = 2000
    SPIN_RANGE = -1.2, 1.2
    NORTH, EAST, SOUTH, WEST = range(4)

    def __init__(self, parent):
        Sprite.__init__(self, parent)
        self.step = (0, 0)
        self.shot_speed_nodeset = self.get_game().interpolator.\
                                  get_nodeset("shot-speed")
        self.add_frames()
        self.shadow = load("Gallery.png").convert_alpha()
        self.register(self.fetch_carrot, self.barf)

    def add_frames(self):
        morph_paths = glob(join(self.get_resource("morph"), "*.png"))
        base = load("Calorie.png").convert_alpha()
        self.add_frame(base)
        self.add_frameset(0, name="facing-right")
        self.add_frame(flip(base, True, False))
        self.add_frameset(1, name="facing-left")
        self.set_frameset(randint(1, 2))
        for path in sorted():
            self.add_frame(load(path).convert_alpha())
            self.add_frameset(xrange(2, len(self.frames)), name="shooting")

    def reset(self):
        self.shot_count = 0
        self.clear_aim()
        place_in_rect(self.get_display_surface().get_rect(), self.location,
                      True, self.parent.goal.skull.location.inflate(\
                          [self.SPAWN_MARGIN] * 2))

    def clear_aim(self):
        self.collisions = []
        self.steps = []

    def find_carrot(self):
        self.play(self.fetch_carrot, delay=self.FETCH_DELAY, play_once=True)

    def fetch_carrot(self):
        step = self.step = get_step(self.location.midbottom,
                                    self.parent.carrot.location.center,
                                    self.SPEED)
        if step[0] < 0:
            self.set_frameset("facing-left")
        else:
            self.set_frameset("facing-right")

    def aim(self):
        angles = deque(xrange(360))
        angles.rotate(randrange(0, len(angles)))
        magnitude = self.shot_speed_nodeset.get_y(self.shot_count)
        bounds = self.get_display_surface().get_rect()
        spin = uniform(*self.SPIN_RANGE)
        best_wc, best_c, best_s = None, [], []
        for angle in angles:
            collides, wall_count, collisions, steps = self.project(angle, spin,
                                                                   magnitude,
                                                                   bounds)
            if collides and wall_count >= best_wc and \
                   len(steps) >= len(best_s) and len(collisions) <= \
                   len(best_c) + 1:
                best_wc = wall_count
                best_c = collisions
                best_s = steps
        self.steps = best_s
        self.collisions = best_c
        self.shot_count += 1
        self.set_frameset("shooting")
        self.play(self.barf, delay=3000, play_once=True)

    def project(self, angle, spin, magnitude, bounds):
        traveled = 0
        projection = Vector(*self.get_game().carrot.location.center)
        collides = False
        steps = []
        collisions = []
        walls = [False] * 4
        while traveled < self.PROJECTION_LENGTH:
            delta = get_delta(angle, magnitude)
            projection += delta
            angle += spin
            if steps and collide_line_with_rect(self.get_game().goal.skull.\
                                                location, steps[-1],
                                                projection):
                collides = True
                break
            if projection[0] < bounds.left or projection[0] > bounds.right or \
                   projection[1] < bounds.top or projection[1] > bounds.bottom:
                if projection[0] < bounds.left:
                    projection[0] += 2 * (bounds.left - projection[0])
                    wall_angle = 0
                    walls[self.WEST] = True
                elif projection[0] > bounds.right:
                    projection[0] += 2 * (bounds.right - projection[0])
                    wall_angle = 0
                    walls[self.EAST] = True
                if projection[1] < bounds.top:
                    projection[1] += 2 * (bounds.top - projection[1])
                    wall_angle = 180
                    walls[self.NORTH] = True
                elif projection[1] > bounds.bottom:
                    projection[1] += 2 * (bounds.bottom - projection[1])
                    wall_angle = 180
                    walls[self.SOUTH] = True
                collisions.append(map(int, projection))
                angle = wall_angle - angle
            steps.append(tuple(projection))
            traveled += magnitude
        wall_count = 0
        for wall in walls:
            if wall:
                wall_count += 1
        return collides, wall_count, collisions, steps

    def barf(self):
        self.get_game().carrot.spawn()
        self.clear_aim()

    def update(self):
        self.get_game().time_filter.open()
        ds = self.get_display_surface()
        for ii in xrange(1, len(self.steps)):
            line(ds, (0, 0, 0), self.steps[ii - 1], self.steps[ii], 5)
            line(ds, (128, 128, 128), self.steps[ii - 1], self.steps[ii], 3)
            line(ds, (0, 255, 255), self.steps[ii - 1], self.steps[ii])
        for ii, collision in enumerate(self.collisions):
            font = Font(None, 20)
            surface = font.render(str(ii), False, (0, 0, 255))
            circle(ds, (255, 255, 255), collision, 20)
            ds.blit(surface, collision)
        if self.step != (0, 0):
            if self.parent.carrot.location.inflate(self.CARROT_BOX_SHRINK).\
                   collidepoint(self.location.midbottom - ):
                self.step = (0, 0)
                self.get_game().time_filter.close()
                self.aim()
            else:
                self.move(*self.step)
        Sprite.update(self)


if __name__ == "__main__":
    iQue().run()
216.73.216.214
216.73.216.214
216.73.216.214
 
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 😇