from os import listdir
from os.path import join

from pygame.mixer import Channel, Sound, music, find_channel

from GameChild import *
from Input import *

class Audio(GameChild):

    current_channel = None
    paused = False
    muted = False

    def __init__(self, game):
        GameChild.__init__(self, game)
        self.delegate = self.get_delegate()
        self.load_fx()
        self.subscribe(self.respond)

    def load_fx(self):
        fx = {}
        if self.get_configuration().has_option("audio", "sfx-path"):
            root = self.get_resource("audio", "sfx-path")
            if root:
                for name in listdir(root):
                    fx[name.split(".")[0]] = Sound(join(root, name))
        self.fx = fx

    def respond(self, event):
        if self.delegate.compare(event, "mute"):
            self.mute()

    def mute(self):
        self.muted = True
        self.set_volume()

    def unmute(self):
        self.muted = False
        self.set_volume()

    def set_volume(self):
        volume = int(not self.muted)
        music.set_volume(volume)
        if self.current_channel:
            self.current_channel.set_volume(volume)

    def play_bgm(self, path, stream=False):
        self.stop_current_channel()
        if stream:
            music.load(path)
            music.play(-1)
        else:
            self.current_channel = Sound(path).play(-1)
        self.set_volume()

    def stop_current_channel(self):
        music.stop()
        if self.current_channel:
            self.current_channel.stop()
        self.current_channel = None
        self.paused = False

    def play_fx(self, name, panning=.5):
        if not self.muted:
            channel = find_channel(True)
            if panning != .5:
                offset = 1 - abs(panning - .5) * 2
                if panning < .5:
                    channel.set_volume(1, offset)
                else:
                    channel.set_volume(offset, 1)
            channel.play(self.fx[name])

    def pause(self):
        channel = self.current_channel
        paused = self.paused
        if paused:
            music.unpause()
            if channel:
                channel.unpause()
        else:
            music.pause()
            if channel:
                channel.pause()
        self.paused = not paused

    def is_bgm_playing(self):
        current = self.current_channel
        if current and current.get_sound():
            return True
        return music.get_busy()
from ld25.pgfw.Setup import Setup

if __name__ == "__main__":
    Setup().setup()
from pgfw.SetupWin import SetupWin

if __name__ == "__main__":
    SetupWin().setup()
from antidefense.pgfw.Configuration import TypeDeclarations

class Types(TypeDeclarations):

    additional_defaults = {
        
        "map": {

            "int": "magnitude"},

        "stamps": {

            "int": ["tile-size", "count", "resolution", "max-magnification",
                    "section-resolution"],
            
            "list": ["palette-0", "palette-1", "palette-2", "palette-3",
                     "palette-4", "palette-5", "palette-6", "palette-7",
                     "palette-8",],
            
            "float-list": "projection-vector"},

        "scale": {

            "int-list": ["bar-dimensions", "offset"],
            
            "list": ["prefixes", "colors"],
            
            "int": ["resolution", "segments", "font-size", "font-padding",
                    "bar-alpha", "stroke-size"]}

            };
from time import sleep

import pygame

from antidefense.pgfw.Game import Game
from antidefense.Types import Types
from antidefense.map.Map import Map

class Antidefense(Game):

    def __init__(self):
        Game.__init__(self, type_declarations=Types())
        self.map.activate()

    def set_children(self):
        Game.set_children(self)
        self.map = Map(self)

    def update(self):
        self.map.update()
        self.get_screen().fill((0, 0, 255), (153, 222, 60, 45))
from time import time
from random import choice

from pygame import Surface, Color

from antidefense.pgfw.GameChild import GameChild

class Layer(GameChild, Surface):

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

    def init_surface(self):
        Surface.__init__(self, self.parent.get_size())

    def randomize(self):
        w, h = self.get_size()
        parent = self.parent
        stamps = parent.stamps.get_stamps(parent.get_zoom_level())
        step = stamps[0].get_width()
        start = time()
        for y in range(0, h, step):
            for x in range(0, w, step):
                self.blit(choice(stamps), (x, y))
        print time() - start
from math import sqrt
from random import choice, randint

from pygame import Color, Surface

from antidefense.pgfw.GameChild import GameChild

class Stamps(GameChild, list):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.config = self.get_configuration("stamps")

    def reset(self):
        list.__init__(self, [])
        self.load_palette()
        self.populate()

    def load_palette(self):
        config = self.config
        resolution = config["section-resolution"]
        parent = self.parent
        w, h = parent.dimensions
        x, y = parent.target
        index = int(float(x) / w * resolution) + resolution * \
                int(float(y) / h * resolution)
        self.palette = map(Color, config["palette-" + str(index)])

    def populate(self):
        config = self.config
        resolution = config["resolution"]
        max_magnification = config["max-magnification"]
        magnification_step = float(max_magnification) / resolution
        magnification = 1
        for ii in range(resolution):
            self.append([])
            while len(self[ii]) < config["count"]:
                saturation = float(ii) / resolution
                self[ii].append(self.build_stamp(saturation,
                                                 int(magnification)))
            magnification += magnification_step

    def build_stamp(self, saturation, magnification):
        size = self.config["tile-size"] * magnification
        stamp = Surface((size, size))
        self.randomize_stamp(stamp, saturation, magnification)
        return stamp

    def randomize_stamp(self, stamp, saturation, magnification):
        w, h = stamp.get_size()
        for y in range(0, h, magnification):
            for x in range(0, w, magnification):
                stamp.fill(self.get_random_color(saturation),
                          (x, y, magnification, magnification))
            
    def get_random_color(self, saturation):
        color = choice(self.palette)
        pr, pg, pb = self.config["projection-vector"]
        r, g, b = color[0], color[1], color[2]
        p = sqrt(r ** 2 * pr + g ** 2 * pg + b ** 2 * pb)
        r = int(p + (r - p) * saturation)
        g = int(p + (g - p) * saturation)
        b = int(p + (b - p) * saturation)
        return self.convert_rgb(r, g, b)

    def convert_rgb(self, r, g, b):
        rgb = [hex(x)[2:].zfill(2) for x in (r, g, b)]
        return Color("#" + "".join(rgb))

    def get_stamps(self, zoom_level):
        return self[int((len(self) - 1) * zoom_level)]
44.210.21.70
44.210.21.70
44.210.21.70
 
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 😇