from random import randrange
from os import listdir
from os.path import join

from pygame import image

from xenographic_wall.pgfw.GameChild import GameChild
from xenographic_wall.world.mushrooms.Mushroom import Mushroom

class Mushrooms(GameChild, list):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.subscribe_to(self.get_custom_event_id(), self.respond_to_event)
        self.load_images()
        self.reset()

    def respond_to_event(self, evt):
        if self.is_command(evt, "reset-game"):
            self.reset()

    def load_images(self):
        images = []
        root = self.get_resource("mushrooms", "path")
        files = self.get_configuration("mushrooms", "images")
        for path in listdir(root):
            parent = join(root, path)
            images.append(
                (image.load(join(parent, files[0])).convert_alpha(),
                 image.load(join(parent, files[1])).convert_alpha()))
        self.images = images

    def reset(self):
        self.populate()

    def populate(self):
        images = self.images
        count = self.get_configuration().get("mushrooms", "count")
        group_count = len(images)
        list.__init__(self, [[] for _ in range(group_count)])
        for ii in range(count):
            self.add_mushroom(ii % group_count)

    def add_mushroom(self, group):
        mushroom = Mushroom(self, group, self.images[group])
        self[group].append(mushroom)
        return mushroom

    def replace_mushroom(self, mushroom):
        group = mushroom.group
        self[group].remove(mushroom)
        self.add_mushroom(group)

    def update(self):
        for group in self:
            for mushroom in group:
                mushroom.update()
from time import time
from collections import deque

from pygame import Surface, Color, mouse, draw

from xenographic_wall.pgfw.GameChild import *
from xenographic_wall.world.scope.chain.Chain import Chain

class Scope(GameChild):

    transparent_color = Color("magenta")

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.subscribe_to(self.get_custom_event_id(), self.respond_to_event)
        self.chain = Chain(self)
        self.deactivate()
        self.reset()

    def activate(self):
        self.active = True

    def deactivate(self):
        self.active = False

    def respond_to_event(self, evt):
        if self.active:
            is_command = self.is_command
            if is_command(evt, "mouse-down-left"):
                self.respond_to_set()
            if is_command(evt, "mouse-down-right"):
                self.respond_to_set_and_reel()
            if is_command(evt, "reel"):
                self.respond_to_reel()

    def respond_to_set(self):
        if not self.flash_start:
            self.place()

    def hide(self):
        self.chain.hide()

    def collide_click(self):
        return self.chain.collidepoint(self.parent.get_mouse_pos())

    def respond_to_set_and_reel(self):
        if not self.flash_start:
            if self.chain.is_hidden() or not self.collide_click():
                self.place()
            self.activate_flash()

    def place(self):
        self.chain.place(self.parent.get_mouse_pos())

    def activate_flash(self):
        self.flash_start = time()
        self.chain.set_color_to_flash()
#         self.show()

    def show(self):
        self.chain.show()

    def respond_to_reel(self):
        self.activate_flash()

    def reset(self):
        chain = self.chain
        chain.reset()
        self.deactivate_flash()
        chain.hide()

    def deactivate_flash(self):
        self.flash_start = None
        self.chain.set_color_to_default()

    def update(self):
        if self.active:
            self.update_flash()
            self.chain.update()

    def update_flash(self):
        start = self.flash_start
        config = self.get_configuration().get_section("scope")
        chain = self.chain
        if start:
            if time() - start > config["flash-length"]:
                self.deactivate_flash()
                chain.set_color_to_default()
            else:
                chain.rotate_colors()
from collections import deque

from pygame import Rect, Color, mouse

from xenographic_wall.pgfw.GameChild import GameChild
from xenographic_wall.world.scope.chain.Ring import Ring

class Chain(GameChild, Rect):

    transparent_color = Color("green")
    
    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.init_rect()
        self.set_rings()
        self.subscribe_to(self.get_custom_event_id(), self.respond_to_event)
        self.reset()

    def init_rect(self):
        width = self.get_configuration("scope", "diameter")
        Rect.__init__(self, 0, 0, width, width)

    def set_rings(self):
        rings = []
        for ii in range(self.get_configuration("scope", "ring-count")):
            rings.append(Ring(self, ii))
        self.rings = rings

    def respond_to_event(self, evt):
        if self.parent.active:
            if self.is_command(evt,"mouse-scroll-up"):
                self.glow()
            if self.is_command(evt, "mouse-scroll-down"):
                self.darken()

    def glow(self):
        max_alpha = 255
        rings = list(reversed(self.rings))
        threshold = max_alpha / len(rings)
        for ii, ring in enumerate(rings):
            if ii == 0 or rings[ii - 1].get_alpha() >= threshold:
                alpha = ring.get_alpha() + self.get_glow_step()
                if alpha > max_alpha:
                    alpha = max_alpha
                ring.set_alpha(alpha)

    def get_glow_step(self):
        return self.get_configuration("scope", "glow-step")

    def darken(self):
        for ring in self.rings:
            alpha = ring.get_alpha() - self.get_glow_step()
            if alpha < 0:
                alpha = 0
            ring.set_alpha(alpha)

    def reset(self):
        self.hide()
        self.set_color_to_default()

    def hide(self):
        for ring in self.rings:
            ring.set_alpha(0)

    def show(self):
        for ring in self.rings:
            ring.set_alpha(255)

    def place(self, pos):
        self.center = pos
        for ring in self.rings:
            ring.rect.center = pos

    def set_color_to_default(self):
        self.colors = deque(map(Color,
                                self.get_configuration("scope", "colors")))
        self.update_colors()

    def update_colors(self):
        for ii, ring in enumerate(self.rings):
            ring.set_color(self.colors[ii])

    def set_color_to_flash(self):
        self.colors = deque(map(Color,
                                self.get_configuration("scope", "flash-colors")))
        self.update_colors()

    def rotate_colors(self):
        self.colors.rotate(1)
        self.update_colors()

    def is_hidden(self):
        for ring in self.rings:
            if ring.get_alpha() > 0:
                return False
        return True

    def update(self):
        for ring in self.rings:
            ring.update()
18.220.60.154
18.220.60.154
18.220.60.154
 
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 😇