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()
# -*- coding: utf-8 -*-

from os import listdir
from os.path import join
from math import sin, cos, radians, sqrt
from random import randint, randrange, choice, random
from copy import deepcopy
import codecs

from pygame import Surface, Color, PixelArray
from pygame.image import load, save
from pygame.draw import circle, arc, aaline, line, ellipse, rect as draw_rect
from pygame.font import Font
from pygame.mixer import Sound
from pygame.event import clear
from pygame.locals import *

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

class LakeOfHeavenlyWind(Game):

    def __init__(self):
        Game.__init__(self)
        self.title.activate()

    def set_children(self):
        Game.set_children(self)
        self.high_scores = HighScores(self)
        self.title = Title(self)
        self.game_screen = GameScreen(self)
        self.book = Book(self)

    def update(self):
        self.title.update()
        self.game_screen.update()
        self.book.update()


class Book(GameChild, list):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        path = self.get_resource("text", "book")
        for block in codecs.open(path, "r", "utf-8").read().split("\n\n"):
            self.append(Hexagram(self, block))

    def hide_indicators(self):
        for hexagram in self:
            hexagram.indicator.hide()

    def hide_explanations(self):
        for hexagram in self:
            hexagram.explanation.hide()

    def are_indicators_hidden(self):
        return all(hexagram.indicator.is_hidden() for hexagram in self)

    def update(self):
        for hexagram in self:
            hexagram.update()


class Hexagram(GameChild):

    TRIGRAM_NAMES = {0b111: "heaven", 0b110: "marsh", 0b101: "fire",
                     0b100: "thunder", 0b11: "wind", 0b10: "water",
                     1: "mountain", 0: "earth"}

    def __init__(self, parent, block):
        GameChild.__init__(self, parent)
        lines = self.lines = block.split("\n")
        self.index = int(lines[0], 2)
        pair = ""
        for ii in xrange(2):
            pair += self.TRIGRAM_NAMES[(self.index & \
                                        (0b111 << ii * 3)) >> (ii * 3)]. \
                                        upper()
            pair += " ABOVE ~ " if not ii else " BELOW"
        lines.insert(2, pair)
        font_path = self.get_resource("display", "font")
        font = Font(font_path, 10)
        explanation = self.explanation = Sprite(self, 4000)
        for line in map(unicode, lines[1:]):
            if line:
                frame = Surface((640, 16), SRCALPHA)
                spaced = line[0]
                for ch in line[1:]:
                    spaced += " " + ch
                caption = font.render(spaced, True, (102, 102, 102))
                rect = caption.get_rect()
                rect.center = frame.get_rect().center
                frame.blit(caption, rect)
                explanation.add_frame(frame)
        explanation.location.center = self.parent.parent.game_screen.link. \
                                  background.location.center
        explanation.hide(),
        indicator = self.indicator = Sprite(self, 500)
        font = Font(font_path, 36)
        font.set_italic(True)
        indicator.add_frame(font.render(lines[1][0], True, (31, 31, 31)))
        blank = Surface(indicator.location.size)
        blank.set_colorkey((0, 0, 0))
        indicator.add_frame(blank)
        rect = self.parent.parent.game_screen.oracle.screens[0].get_rect()
        indicator.location.center = 32 + rect.centerx, 16 + rect.centery
        indicator.add_location(offset=(self.get_display_surface(). \
                                       get_width() - rect.centerx * 2 - 64, 0))
        indicator.hide()

    def show_indicator(self):
        self.indicator.unhide()

    def show_explanation(self):
        self.explanation.get_current_frameset().reset()
        self.explanation.unhide()

    def update(self):
        self.explanation.update()
        self.indicator.update()


class HighScores(GameChild):

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

    def read(self):
        scores = []
        for line in file(self.get_resource("text", "scores")):
            scores.append(int(line))
        return scores

    def add(self, score):
        file(self.get_resource("text", "scores"), "a").write(str(score) + "\n")


class Title(Animation):

    def __init__(self, parent):
        Animation.__init__(self, parent)
        self.time_filter = self.get_game().time_filter
        self.display_surface = self.get_display_surface()
        self.delegate = self.get_game().delegate
        self.music = Sound(self.get_resource("audio", "outer"))
        self.start_fx = SoundEffect(self, "start", .4)
        self.deactivate()
        background = self.background = Sprite(self)
        tile_size = self.tile_size = 8
        for _ in xrange(9):
            tile = Surface((tile_size, tile_size))
            frame = Surface(self.display_surface.get_size())
            for x in xrange(tile.get_width()):
                for y in xrange(tile.get_height()):
                    tile.set_at((x, y), choice([(128, 128, 128), (95, 95, 95)]))
            for x in xrange(0, frame.get_width(), tile.get_width()):
                for y in xrange(0, frame.get_height(), tile.get_height()):
                    frame.blit(tile, (x, y))
            background.add_frame(frame)
        layers = self.layers = []
        key = (255, 0, 255)
        for ii in xrange(3):
            tiles = []
            for _ in xrange(8):
                tile = Surface((tile_size, tile_size))
                tile.fill(key)
                for x in xrange(tile.get_width()):
                    for y in xrange(tile.get_height()):
                        if random() > .885:
                            tile.set_at((x, y), [(255, 255, 80), (80, 255, 255),
                                                 (22, 22, 22)][ii])
                tiles.append(tile)
            layer = Sprite(self)
            frame = Surface((background.location.w + tile_size * (16 + ii),
                             background.location.h + tile_size * (16 + ii)))
            frame.set_colorkey(key)
            for x in xrange(0, frame.get_width(), tile.get_width()):
                for y in xrange(0, frame.get_height(), tile.get_height()):
                    frame.blit(choice(tiles), (x, y))
            layer.add_frame(frame)
            layers.append(layer)
        self.set_pieces()
        self.subscribe(self.respond)
        self.register(self.remap_pieces, interval=1200)
        self.play(self.remap_pieces)

    def set_caption(self):
        caption = self.caption = Sprite(self, 5000)
        font = Font(self.get_resource("display", "font"), 12)
        color = Color(0, 0, 0)
        texts = ["Wind Off of Heaven's Lake", u"澤 天 風"]
        for text in texts:
            spaced = text[0]
            for ch in text[1:]:
                spaced += "  " + ch
            frame = Surface((640, 100), SRCALPHA)
            plate = font.render(spaced.upper(), True, (255, 255, 255))
            rect = plate.get_rect()
            rect.center = frame.get_rect().center
            frame.blit(plate, rect)
            caption.add_frame(frame)
        caption.location.center = self.display_surface.get_rect().centerx, 400
        caption.get_current_frameset().current_index = 1

    def deactivate(self):
        self.active = False
        self.music.fadeout(500)

    def respond(self, event):
        if self.active:
            if self.delegate.compare(event, "advance"):
                self.deactivate()
                self.parent.game_screen.activate()
                self.start_fx.play()

    def activate(self, incoming=None):
        self.active = True
        self.music.play(-1, 0, 500)
        scores = self.scores = []
        count = 5
        for ii, score in enumerate(sorted(self.parent. \
                                          high_scores.read())[-count:]):
            font = Font(self.get_resource("display", "font"), 11 + (ii * 1))
            sprite = Sprite(self, 380)
            sprite.add_frame(font.render(str(score), True, (32, 200, 32),
                                         (112, 240, 240)))
            if score == incoming:
                surface = Surface(sprite.location.size)
                key = (255, 0, 255)
                surface.fill(key)
                surface.set_colorkey(key)
                sprite.add_frame(surface)
            sprite.location.centerx = self.display_surface.get_rect(). \
                                      centerx + 100 * ((count - ii - 1) - \
                                                       count / 2.0 + .5)
            scores.append(sprite)
        self.set_caption()
        clear()

    PIECE_RADIUS = 40
    PIECE_COLORS = (255, 255, 0, 255), (255, 255, 0, 255)

    def set_pieces(self):
        self.blank_piece_map = [[(False, 0), (False, 0)], [(False, 0), (False, 0)]]
        self.piece_map = deepcopy(self.blank_piece_map)
        self.remap_pieces()

    def remap_pieces(self):
        previous = deepcopy(self.piece_map)
        while self.piece_map == previous or self.piece_map == self.blank_piece_map:
            print self.piece_map, self.blank_piece_map, previous
            for x in xrange(len(self.piece_map[0])):
                for y in xrange(len(self.piece_map)):
                    self.piece_map[x][y] = choice((True, False)), choice((0, 1))

    def update(self):
        Animation.update(self)
        if self.active:
            self.background.update()
            ds = self.display_surface
            for ii, layer in enumerate(reversed(self.layers)):
                if ii == 0:
                    layer.move(-.25, -.25)
                    if layer.location.right < ds.get_width():
                        layer.move(self.tile_size * 16, self.tile_size * 16)
                elif ii == 1:
                    layer.move(-.5)
                    if layer.location.right < ds.get_width():
                        layer.move(self.tile_size * 16)
                elif ii == 2:
                    layer.move(.5, .5)
                    if layer.location.left > 0:
                        layer.move(-self.tile_size * 16, -self.tile_size * 16)
                layer.update()
            intermediate = Surface(ds.get_size(), SRCALPHA)
            intermediate = Surface((300, 300))
            circle(intermediate, (0, 255, 255),
                   (149, 149), 149)
            rect = intermediate.get_rect()
            rect.center = ds.get_rect().center
            ds.blit(intermediate, rect, None, BLEND_RGB_SUB)
            # for xi, x in enumerate(xrange(160, 560, 320)):
            #     for yi, y in enumerate(xrange(120, 440, 240)):
            #         if self.piece_map[xi][yi][0]:
            #             circle(intermediate, (0, 0, 0, 255), (x - 1, y + 1), self.PIECE_RADIUS)
            #             circle(intermediate, self.PIECE_COLORS[self.piece_map[xi][yi][1]],
            #                    (x + 1, y - 1), self.PIECE_RADIUS)
                    # else:
                    #     for radius in xrange(20, 0, -4):
                    #         circle(ds, (randrange(0, 255), randrange(0, 255), randrange(0, 255)), (x, y), radius)
            # color = choice([(22, 22, 22), (255, 0, 0), (0, 255, 255), (255, 255, 255)])
            # ds.blit(intermediate, (0, 0), None, BLEND_RGB_SUB)
            # draw_rect(ds, color, ds.get_rect().inflate(-4, -4), 1)
            # for score in self.scores:
            #     score.update()
            # self.caption.update()


class SoundEffect(GameChild, Sound):

    def __init__(self, parent, name, volume=1.0):
        GameChild.__init__(self, parent)
        Sound.__init__(self, self.get_resource("audio", name))
        self.name = name
        self.set_volume(volume)

    def play(self, position=.5):
        channel = Sound.play(self)
        right = 1 + min(0, ((position - .5) * 2))
        left = 1 - max(0, ((position - .5) * 2))
	if channel is not None:
            channel.set_volume(left, right)


class GameScreen(GameChild):

    PALETTE = [[(191, 191, 220), (191, 255, 191)],
               [(191, 191, 220), (255, 191, 191)],
               [(191, 191, 225), (191, 255, 191)],
               [(191, 191, 255), (255, 191, 191)],
               [(191, 220, 191), (191, 191, 255)],
               [(191, 220, 191), (255, 191, 191)],
               [(191, 255, 191), (255, 191, 191)],
               [(220, 191, 191), (191, 191, 255)],
               [(220, 191, 191), (191, 255, 191)]]

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.delegate = self.get_game().delegate
        self.time_filter = self.get_game().time_filter
        self.display_surface = self.get_display_surface()
        self.music = Sound(self.get_resource("audio", "inner"))
        self.music.set_volume(.8)
        self.previous_palette = None
        self.wave = 0
        self.deactivate()
        self.set_background()
        self.pulp = Pulp(self)
        self.link = Link(self)
        self.paddles = Paddles(self)
        self.rails = Rails(self)
        self.oracle = Oracle(self)
        self.subscribe(self.respond)

    def set_background(self):
        w, h = 8, 8
        tile = Surface((w, h))
        while True:
            palette = choice(self.PALETTE)
            if self.previous_palette != palette:
                self.previous_palette = palette
                break
        for x in xrange(w):
            for y in xrange(h):
                tile.set_at((x, y), palette[(x + y) % 2])
        background = self.background = Surface(self.display_surface.get_size())
        for x in xrange(0, background.get_width(), w):
            for y in xrange(0, background.get_height(), h):
                background.blit(tile, (x, y))

    def activate(self):
        self.active = True
        self.ending = False
        self.game_over_elapsed = 0
        self.music.play(-1)
        self.wave = 0
        self.pulp.reset()
        self.rails.reset()
        self.oracle.clear()
        self.introduce()
        self.paddles.set_background()
        self.paddles.reset_position()
        self.paddles.arrange_graticules(0)
        self.set_background()

    def introduce(self):
        self.freeze()
        self.introducing = True
        self.introducing_elapsed = 0

    def increase_wave(self):
        self.wave += 1
        self.paddles.explode_mines()
        self.paddles.set_background()
        self.paddles.reset_position()
        self.paddles.arrange_graticules(0)
        self.rails.increase_spawn_rate()
        self.introduce()
        self.rails.clear_phages()
        self.rails.set_deviation()
        self.set_background()
        self.pulp.health += 1.0 / 6
        if self.pulp.health > .9999:
            self.pulp.health = .9999
        self.parent.book.hide_indicators()

    def freeze(self):
        self.frozen = True

    def unfreeze(self):
        self.frozen = False

    def is_frozen(self):
        return self.frozen

    def deactivate(self):
        self.active = False
        self.music.stop()

    def end(self):
        self.freeze()
        self.ending = True
        self.parent.high_scores.add(int(self.pulp.score))
        self.paddles.explode_mines()
        self.paddles.reset_position()
        self.oracle.animals.hide()
        for hexagram in self.parent.book:
            if not hexagram.explanation.is_hidden():
                hexagram.explanation.halt()

    def respond(self, event):
        if self.active and self.ending and self.game_over_elapsed > 3000 and \
               self.delegate.compare(event, "advance"):
            self.parent.book.hide_explanations()
            self.parent.book.hide_indicators()
            self.deactivate()
            self.parent.title.activate(int(self.pulp.score))

    def update(self):
        if self.active:
            self.display_surface.blit(self.background, (0, 0))
            if self.introducing:
                font = Font(self.get_resource("display", "font"), 10)
                text = "WAVE " + str(self.wave)
                spaced = text[0]
                for ch in text[1:]:
                    spaced += "  " + ch
                text = font.render(spaced, True, (31, 31, 31))
                rect = text.get_rect()
                rect.center = self.display_surface.get_rect().centerx, 260
                self.display_surface.blit(text, rect)
                if self.introducing_elapsed > 2000:
                    self.introducing = False
                    self.unfreeze()
                else:
                    self.introducing_elapsed += self.time_filter. \
                                                get_last_frame_duration()
            elif self.ending:
                font = Font(self.get_resource("display", "font"), 10)
                text = font.render("G  A  M  E     O  V  E  R", True,
                                   (31, 31, 31))
                rect = text.get_rect()
                rect.center = self.display_surface.get_rect().centerx, 260
                self.display_surface.blit(text, rect)
                self.game_over_elapsed += self.time_filter. \
                                          get_last_frame_duration()
            self.oracle.animals.update()
            self.pulp.update()
            if not self.is_frozen():
                self.rails.update()
            self.paddles.update()
            self.link.update()
            self.oracle.update()


class Pulp(GameChild, Surface):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.display_surface = self.get_display_surface()
        self.font = Font(self.get_resource("display", "font"), 24)
        self.explosions = [Explosion(self) for _ in xrange(32)]
        self.lose_health_fx = SoundEffect(self, "lose-health")
        self.blow_up_fx = SoundEffect(self, "blow-up", .8)
        self.reset()
        Surface.__init__(self, (self.display_surface.get_width(), 96))
        self.rect = self.get_rect()
        indicators = self.indicators = []
        root = self.get_resource("image", "pulp")
        for path in sorted(listdir(root)):
            indicator = Sprite(self, 5500)
            image = load(join(root, path))
            image_r = self.image_r = image.get_rect()
            width = self.get_width()
            height = (self.rect.h / image_r.h + 2) * image_r.h
            color = Color(0, 0, 0)
            for hue in [-150, -128, 149]:
                pixels = PixelArray(image.copy())
                for x in xrange(len(pixels)):
                    for y in xrange(len(pixels[0])):
                        color = Color(*image.unmap_rgb(pixels[x][y]))
                        h, s, l, a = color.hsla
                        color.hsla = round((h + hue) % 360), round(s), \
                                     round(l), round(a)
                        pixels[x][y] = color
                plate = pixels.make_surface()
                frame = Surface((width, height), SRCALPHA)
                for x in xrange(0, width, image_r.w):
                    for y in xrange(0, height, image_r.h):
                        frame.blit(plate, (x, y))
                indicator.add_frame(frame)
                indicator.display_surface = self
            indicators.append(indicator)
        self.score_backgrounds = []
        tile = Surface((2, 2))
        for x in xrange(tile.get_width()):
            for y in xrange(tile.get_height()):
                tile.set_at((x, y), [(220, 220, 220),
                                     (128, 128, 128)][(x + y) % 2])
        for _ in xrange(8):
            surface = Surface((22, 26))
            for x in xrange(0, surface.get_width(), tile.get_width()):
                for y in xrange(0, surface.get_height(), tile.get_height()):
                    surface.blit(tile, (x, y))
            self.score_backgrounds.append(surface)

    def reset(self):
        self.health = .9999
        self.score = 0
        for explosion in self.explosions:
            explosion.reset()

    def update(self):
        for indicator in self.indicators:
            indicator.move(dy=-1)
            if indicator.location.top < -self.image_r.h:
                indicator.move(dy=self.image_r.h)
        self.indicators[int(self.health * len(self.indicators))].update()
        self.display_surface.blit(self, self.rect)
        # if not self.parent.is_frozen():
        #     self.score += self.health * .1
        text = str(int(self.score))
        color = randint(0, 120), randint(0, 120), randint(0, 120)
        for ii, digit in enumerate(text):
            background = self.score_backgrounds[ii]
            br = background.get_rect()
            br.centerx = 40 * (ii - len(text) / 2.0 + .5) + \
                         self.display_surface.get_rect().centerx
            self.display_surface.blit(self.score_backgrounds[ii], br)
            glyph = self.font.render(digit, True, color)
            gr = glyph.get_rect()
            gr.centerx = br.centerx
            self.display_surface.blit(glyph, gr)
        outgoing = []
        for phage in self.parent.rails.phages:
            if phage.get_center()[1] <= self.rect.centery:
                outgoing.append(phage)
                self.health -= .05
                for explosion in self.explosions:
                    if explosion.is_hidden():
                        explosion.get_current_frameset().reset()
                        explosion.location.center = phage.get_center()
                        explosion.unhide()
                        break
                if self.health < 0:
                    self.parent.end()
                    break
        if outgoing:
            total = 0
            for phage in outgoing:
                total += phage.get_center()[0]
                self.parent.rails.phages.remove(phage)
            position = float(total) / len(outgoing) / \
                       self.get_display_surface().get_width()
            self.lose_health_fx.play(position)
            self.blow_up_fx.play(position)
        for explosion in self.explosions:
            explosion.update()


class Explosion(Sprite):

    def __init__(self, parent):
        Sprite.__init__(self, parent)
        count = 32
        color = Color(0, 0, 0)
        for ii in xrange(count):
            frame = Surface((64, 64), SRCALPHA)
            ratio = float(ii) / count
            color.hsla = 60 - ratio * 60, 100, 50, 100 - ratio * 100
            fr = frame.get_rect()
            circle(frame, color, fr.center, 6 + int(ratio * (fr.w / 2 - 6)), 5)
            self.add_frame(frame)
        self.reset()

    def reset(self):
        self.hide()

    def shift_frame(self):
        Sprite.shift_frame(self)
        frameset = self.get_current_frameset()
        if frameset.current_index == frameset.length() - 1:
            self.hide()


class Link(GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.display_surface = self.get_display_surface()
        self.background = Sprite(self, 500)
        tile = Surface((2, 2))
        for x in xrange(tile.get_width()):
            for y in xrange(tile.get_height()):
                tile.set_at((x, y), [(255, 255, 0), (228, 228, 228)][(x + y) % 2])
        for jj in xrange(3):
            frame = Surface((self.display_surface.get_width(), 24))
            for x in xrange(0, frame.get_width(), tile.get_width()):
                for y in xrange(0, frame.get_height(), tile.get_height()):
                    frame.blit(tile, (x, y))
            for ii, x in enumerate(xrange(-4, frame.get_width(), 16)):
                colors = [(63, 255, 63), (240, 240, 63), (191, 31, 220)]
                primary_color = colors[(ii - jj) % 3]
                secondary_color = colors[(ii - jj + 1) % 3]
                frame.fill(primary_color, (x, 0, 8, 3))
                frame.fill(secondary_color, (x + 2, 1, 4, 2))
                frame.fill(primary_color, (x, frame.get_height() - 3, 8, 3))
                frame.fill(secondary_color, (x + 2, frame.get_height() - 3, 4,
                                             2))
            self.background.add_frame(frame)
        self.background.location.top = self.parent.pulp.get_rect().bottom

    def update(self):
        self.background.update()


class Paddles(GameChild):

    LEFT, RIGHT = range(2)
    GRATICULES = (((0, 0),),
                  ((.5, 270), (.5, 90)),
                  ((.5, 0), (.5, 180)),
                  ((.5, 45), (.5, 225)),
                  ((.5, 135), (.5, 315)),
                  ((1.0, 0), (0, 0), (1.0, 180)),
                  ((1.0, 45), (0, 0), (1.0, 225)),
                  ((1.0, 135), (0, 0), (1.0, 315)),
                  ((.5774, 0), (.5774, 120), (.5774, 240)))

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.time_filter = self.get_game().time_filter
        self.display_surface = self.get_display_surface()
        self.delegate = self.get_game().delegate
        self.detonate_mine_fx = SoundEffect(self, "detonate", .8)
        self.drop_mine_fx = SoundEffect(self, "drop", .3)
        self.eliminate_phage_fx = SoundEffect(self, "eliminate", 1)
        self.graticule_y = 0
        self.set_background()
        self.set_lattice()
        self.set_paddles()
        self.graticule = Graticule(self)
        self.arrange_graticules(0)
        self.mines = [Mine(self) for _ in xrange(16)]
        self.active_mines = [[], []]
        self.subscribe(self.respond)

    def set_background(self):
        background = self.background = Sprite(self, 120)
        mask = Surface((8, 8), SRCALPHA)
        for x in xrange(mask.get_width()):
            for y in xrange(mask.get_height()):
                mask.set_at((x, y), [(255, 255, 255, 255),
                                     (255, 255, 255, 0)][(x + y) % 2])
        color = Color(0, 0, 0)
        count = 16
        h = 32
        hue_ii = 0
        hue_base = randrange(0, 360)
        for ii in xrange(count):
            frame = Surface((self.display_surface.get_width(), h), SRCALPHA)
            for y in xrange(h):
                hue = 30 * (float(hue_ii) / (count / 2)) + hue_base
                if hue >= 360:
                    hue -= 360
                color.hsla = hue, 100, 50, 100 * (float(y) / h)
                frame.fill(color, (0, y, frame.get_width(), 1))
            hue_ii += 1 if ii < count / 2 else -1
            for x in xrange(0, frame.get_width(), mask.get_width()):
                for y in xrange(0, h, mask.get_height()):
                    frame.blit(mask, (x, y), None, BLEND_RGBA_MIN)
            background.add_frame(frame)
        background.location.bottom = self.get_display_surface().get_rect(). \
                                     bottom

    def set_lattice(self):
        mask = load(self.get_resource("image", "plateau")).convert_alpha()
        tile = Surface((9, 9))
        tw, th = tile.get_size()
        for x in xrange(tw):
            for y in xrange(th):
                tile.set_at((x, y), [(0, 255, 255), (255, 0, 255),
                                     (255, 255, 0)][(x + y) % 3])
        w, h = self.background.location.size
        w += mask.get_width()
        base = Surface((w, h), SRCALPHA)
        for x in xrange(0, w, tw):
            for y in xrange(0, h, th):
                base.blit(tile, (x, y))
        for x in xrange(0, w, mask.get_width()):
            base.blit(mask, (x, 0), None, BLEND_RGBA_MIN)
        lattice = self.lattice = Sprite(self)
        lattice.add_frame(base)
        lattice.location.bottom = self.get_display_surface().get_rect().bottom + 2

    def set_paddles(self):
        image = load(self.get_resource("image", "paddle")).convert_alpha()
        self.paddle_length = image.get_width()
        margin = self.margin = (self.get_display_surface().get_width() / 2) - \
                 self.paddle_length
        surface = Surface((image.get_width() * 2 + margin, image.get_height()))
        key = (255, 0, 255)
        surface.fill(key)
        surface.set_colorkey(key)
        surface.blit(image, (0, 0))
        surface.blit(image, (image.get_width() + margin, 0))
        paddles = self.paddles = Sprite(self, 60)
        count = 8
        color = Color(0, 0, 0)
        for ii in xrange(count):
            color.hsla = randrange(0, 360), 100, \
                         60 + 40 * (float(ii) / (count - 1)), 100
            pixels = PixelArray(surface.copy())
            pixels.replace((255, 255, 255), color)
            frame = pixels.make_surface()
            frame.set_colorkey(key)
            paddles.add_frame(frame)
        ds = self.get_display_surface()
        paddles.add_location()
        self.reset_position()
        self.reset_throttle()

    def reset_position(self):
        self.moving = [False, False]
        ds = self.get_display_surface()
        for ii, location in enumerate(self.paddles.locations):
            location.midbottom = ds.get_rect().centerx, \
                                 ds.get_height() - 15
            if ii == 1:
                location.left += ds.get_width()

    def reset_throttle(self):
        self.throttle = [0, 0]

    def arrange_graticules(self, index=None):
        if index is None:
            index = randrange(1, len(self.GRATICULES))
        if index < 5:
            if index == 3:
                states = self.GRATICULES[index], self.GRATICULES[index + 1]
            elif index == 4:
                states = self.GRATICULES[index], self.GRATICULES[index - 1]
            else:
                states = self.GRATICULES[index], self.GRATICULES[index]
        else:
            if randint(0, 1):
                states = self.GRATICULES[index], self.GRATICULES[0]
            else:
                states = self.GRATICULES[0], self.GRATICULES[index]
        graticule = self.graticule
        graticule.remove_locations()
        initialized = False
        y = self.graticule.location.centery
        for ii, state in enumerate(states):
            if not ii:
                x = self.paddles.location.left + self.paddle_length / 2
            else:
                x = self.paddles.location.right - self.paddle_length / 2
            for offset in state:
                margin = 60
                dx = margin * offset[0] * sin(radians(offset[1]))
                dy = margin * offset[0] * - cos(radians(offset[1]))
                center = int(float(x + dx)), int(float(y + dy))
                if not initialized:
                    graticule.location.center = center
                    graticule.location.side = self.LEFT
                    initialized = True
                else:
                    location = graticule.add_location((0, 0))
                    location.side = ii
                    location.center = center

    def explode_mines(self):
        count = 0
        total_x = 0
        for side in self.active_mines:
            for mine in side:
                count += 1
                total_x += mine.location.centerx
                mine.set_frameset("explode")
        for location in self.graticule.locations:
            location.unhide()
        if count:
            self.detonate_mine_fx.play(float(total_x) / count / \
                                       self.get_display_surface().get_width())

    def respond(self, event):
        if self.parent.active and not self.parent.ending:
            compare = self.delegate.compare
            if compare(event, "left") or compare(event, "left", True):
                self.moving[self.LEFT] = not event.cancel
            elif compare(event, "right") or compare(event, "right", True):
                self.moving[self.RIGHT] = not event.cancel
            elif not self.parent.is_frozen() and \
                     (compare(event, "release-left") or \
                      compare(event, "release-right")):
                side = self.LEFT if event.command == "release-left" else self.RIGHT
                if self.active_mines[side]:
                    outgoing = []
                    count = len(self.active_mines[side])
                    mine_total_x = 0
                    hit = []
                    while self.active_mines[side]:
                        mine = self.active_mines[side][0]
                        mine_total_x += mine.location.centerx
                        center = mine.location.center
                        mine.set_frameset("explode")
                        mine.location.center = center
                        mine.get_current_frameset().reset()
                        for phage in self.parent.rails.phages:
                            px, py = phage.get_center()
                            d = sqrt((px - mine.location.centerx) ** 2 + \
                                     (py - mine.location.centery) ** 2)
                            reach = 100
                            if d < reach:
                                start = phage.health
                                phage.health -= 1.5 * (reach - float(d)) / reach
                                if phage.health < 0:
                                    if phage not in (r[0] for r in outgoing):
                                        for record in hit:
                                            if record[0] == phage:
                                                start = record[1]
                                                hit.remove(record)
                                                break
                                        outgoing.append((phage, start))
                                else:
                                    if phage not in (r[0] for r in hit):
                                        hit.append((phage, start))
                        self.active_mines[side].remove(mine)
                    self.detonate_mine_fx.play(float(mine_total_x) / count / \
                                               self.get_display_surface(). \
                                               get_width())
                    increase = 0
                    phage_total_x = 0
                    for record in outgoing:
                        increase += record[1]
                        phage_total_x += record[0].get_center()[0]
                        record[0].play(record[0].die)
                        # self.parent.rails.phages.remove(record[0])
                    self.parent.pulp.score += increase * len(outgoing) * 10
                    if outgoing:
                        self.eliminate_phage_fx.play(float(phage_total_x) / \
                                                     len(outgoing) / \
                                                     self. \
                                                     display_surface. \
                                                     get_width())
                    for location in self.graticule.locations:
                        if location.side == side:
                            location.unhide()
                    self.throttle[side] = 0
                elif self.throttle[side] > 500:
                    total_x = 0
                    for location in self.graticule.locations:
                        if location.side == side:
                            while True:
                                mine = choice(self.mines)
                                if mine.is_hidden():
                                    mine.unhide()
                                    mine.location.center = location.center
                                    mine.get_current_frameset().reset()
                                    break
                            self.active_mines[side].append(mine)
                            total_x += mine.location.centerx
                            location.hide()
                    self.drop_mine_fx.play(float(total_x) / \
                                           len(self.active_mines[side]) / \
                                           self.get_display_surface(). \
                                           get_width())

    def update(self):
        for ii in xrange(len(self.throttle)):
            self.throttle[ii] += self.time_filter.get_last_frame_duration()
        speed = 8
        if self.moving[self.LEFT]:
            self.paddles.move(-speed)
            self.graticule.move(-speed)
        elif self.moving[self.RIGHT]:
            self.paddles.move(speed)
            self.graticule.move(speed)
        ds = self.get_display_surface()
        if self.paddles.location.right < 0:
            self.paddles.move(ds.get_width())
        elif self.paddles.location.right > ds.get_width():
            self.paddles.move(-ds.get_width())
        y = self.graticule.location.centery
        start = self.parent.link.background.rect.bottom
        end = ds.get_height() - 32
        position = (end - y) / float(end - start)
        dy = self.get_game().interpolator.get_nodeset("shoot").get_y(position)
        self.graticule.move(dy=-dy)
        for location in self.graticule.locations:
            if location.right < 0:
                location.move_ip(ds.get_width(), 0)
            elif location.right > ds.get_width():
                location.move_ip(-ds.get_width(), 0)
            if location.top < self.parent.link.background.rect.bottom:
                location.move_ip(0, ds.get_height() - \
                                 self.parent.link.background.rect.bottom - 32)
        self.lattice.move(-.5)
        if self.lattice.location.right < ds.get_rect().right:
            self.lattice.move(ds.get_rect().right - \
                              self.lattice.location.right + 16)
        self.lattice.update()
        if not self.parent.is_frozen():
            self.graticule.update()
        for mine in self.mines:
            mine.update()
        self.paddles.update()
        self.background.update()


class Graticule(Sprite):

    def __init__(self, parent):
        Sprite.__init__(self, parent, 120)
        surface = Surface((14, 14), SRCALPHA)
        rect = surface.get_rect()
        count = 8
        color_ii = 0
        inner_color, outer_color, bg_color = Color(0, 0, 0), Color(0, 0, 0), \
                                             Color(0, 0, 0)
        mid = count / 2
        for ii in xrange(count):
            inner_color.hsla = 80, 50, 40 + 10 * (float(color_ii) / mid), 100
            hue = randrange(0, 360)
            outer_color.hsla = hue, 100, 50, 100
            bg_color.hsla = randrange(0, 360), 100, 50, 16
            frame = surface.copy()
            circle(frame, bg_color, rect.center, 7)
            circle(frame, inner_color, (rect.centerx, rect.centery + 1), 5)
            circle(frame, outer_color, rect.center, 5)
            circle(frame, inner_color, rect.center, 3)
            circle(frame, (0, 0, 0, 0), (rect.centerx, rect.centery + 1), 2)
            self.add_frame(frame)
            color_ii += -1 if ii >= count / 2 else 1


class Mine(Sprite):

    def __init__(self, parent):
        Sprite.__init__(self, parent, 120)
        surface = Surface((20, 20), SRCALPHA)
        particles = []
        distances = [4, 2, 2, 1, 0, 1, 2, 2, 4]
        radii = [2, 2, 2, 2, 2, 2, 2, 2, 2]
        particle_count = 48
        for ii in xrange(particle_count):
            angle = 360 * float(ii) / particle_count
            distance_ii = ii % len(distances)
            particles.append(Particle(ii, angle, distance_ii))
        frame_count = 18
        cx, cy = 10, 10
        self.add_frameset(name="wait", switch=True)
        for frame_ii in xrange(frame_count):
            frame = surface.copy()
            circle(frame, (255, 255, randint(0, 63), randint(100, 160)),
                   (10, 10), 10)
            for particle in sorted(particles, key=lambda p: p.layer):
                distance = distances[particle.distance_ii]
                x = int(round(cx + distance * sin(radians(particle.angle))))
                y = int(round(cy + distance * - cos(radians(particle.angle))))
                circle(frame, particle.color, (x, y),
                       radii[particle.distance_ii])
                particle.distance_ii += 1
                if particle.distance_ii >= len(distances):
                    particle.distance_ii = 0
                    particle.layer += ((len(particles) / 2 - particle.layer) * \
                                       2 - 1)
                if distance == 0:
                    particle.angle = (particle.angle + 180) % 360
            self.add_frame(frame)
        self.add_frameset(name="explode", switch=True)
        surface = Surface((100, 100), SRCALPHA)
        thickness = 6
        color = Color(0, 0, 0)
        for radius in xrange(6, 50, 2):
            frame = surface.copy()
            ratio = float(radius - 6) / (50 - 6)
            color.hsla = 60 * (1 - ratio), 80 + 10 * (1 - ratio), \
                         75 + 18 * (1 - ratio), thickness * 30 * (100 / 255.0)
            circle(frame, color, (50, 50), radius, max(1, int(thickness)))
            thickness -= .2
            self.add_frame(frame)
        self.set_frameset("wait")
        self.hide()

    def shift_frame(self):
        Sprite.shift_frame(self)
        frameset = self.get_current_frameset()
        if frameset.name == "explode":
            if frameset.current_index == frameset.length() - 1:
                self.set_frameset("wait")
                self.hide()


class Particle:

    def __init__(self, ii, angle, distance_ii):
        self.color = Color(0, 0, 0)
        self.color.hsla = 0, 0, randint(0, 100), 100
        self.color = choice([(27, 27, 27), (255, 63, 63), (63, 63, 255),
                             (255, 255, 255)])
        self.angle = angle
        self.layer = ii
        self.distance_ii = distance_ii


class Rails(GameChild, list):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.display_surface = self.get_display_surface()
        self.depth = self.display_surface.get_height() + 4
        self.stray = 128
        self.view_y = 0
        interpolator = self.get_game().interpolator
        self.spawn_nodeset = interpolator.get_nodeset("spawn")
        self.step_nodeset = interpolator.get_nodeset("step")
        margin = 32
        limit = self.display_surface.get_width() - margin
        step = (limit - margin) / 16
        for x in xrange(48, limit, step):
            self.append(Rail(self, x,
                             x > self.display_surface.get_rect().centerx))
        deviations = self.deviations = []
        ii = 1
        while True:
            nodeset = self.get_game().interpolator.get_nodeset("deviation-" + \
                                                               str(ii))
            ii += 1
            if nodeset:
                deviations.append(nodeset)
            else:
                break
        self.set_deviation()
        self.reset()

    def set_deviation(self):
        self.deviation = choice(self.deviations)
        self.set_background()

    def reset(self):
        self.increase_spawn_rate()
        self.clear_phages()

    def clear_phages(self):
        self.phages = []

    def increase_spawn_rate(self):
        self.spawn_rate = self.spawn_nodeset.get_y(self.parent.wave)
        self.phage_step = self.step_nodeset.get_y(self.parent.wave)

    def set_background(self):
        end = self.parent.link.background.location.bottom
        length = self.depth - end
        color = Color(0, 0, 0)
        background = self.background = \
                     Surface(self.get_display_surface().get_size())
        background.set_colorkey((0, 0, 0))
        for ii, y in enumerate(xrange(self.depth, end - 5, -5)):
            dx = self.stray * self.deviation.get_y(float(ii * 5) / length)
            px = self.stray * self.deviation.get_y(float((ii - 1) * 5) / length)
            hue = min(360, int(360 * float(ii * 5) / length))
            color.hsla = hue, 100, 40, 100
            for rail in self:
                modifier = rail.get_modifier()
                line(background, color, (rail.x + px * modifier, y),
                     (rail.x + dx * modifier, y))

    def update(self):
        if random() < self.spawn_rate:
            self.phages.append(Phage(self, choice(self)))
        height = 20
        self.display_surface.blit(self.background, (0, self.view_y),
                                  (0, self.view_y,
                                   self.display_surface.get_width(), height))
        self.view_y -= 3
        if self.view_y + height < self.parent.link.background.location.bottom:
            self.view_y = self.display_surface.get_height() - height
        for phage in self.phages:
            phage.update()


class Rail(GameChild):

    def __init__(self, parent, x, mirrored):
        GameChild.__init__(self, parent)
        self.x = x
        self.mirrored = mirrored

    def get_modifier(self):
        return -1 if self.mirrored else 1


class Phage(Animation):

    TRANSPARENT_COLOR = (255, 0, 255)

    def __init__(self, parent, rail):
        Animation.__init__(self, parent, self.die, 50)
        self.rail = rail
        self.t = 0
        self.health = 1
        body = self.body = []
        self.yr = self.parent.parent.link.background.location.bottom, \
                  self.parent.depth
        for size in xrange(4, 0, -1):
            segment = Sprite(self, 500)
            for ii in xrange(2):
                surface = Surface((size, size))
                surface.fill([(255, 255, 255), (31, 31, 31)][(size + ii) % 2])
                surface.set_colorkey(self.TRANSPARENT_COLOR)
                segment.add_frame(surface)
            body.append(segment)
        center = self.parent.phage_step
        self.step = random() * .004 - .002 + center

    def get_center(self):
        return self.body[0].location.midbottom

    def die(self):
        for segment in self.body:
            alpha = segment.alpha - 48
            if alpha <= 0:
                self.parent.phages.remove(self)
                self.halt()
                break
            else:
                for _ in xrange(10):
                    w, h = segment.location.size
                    segment.get_current_frame().set_at((randrange(0, w),
                                                        randrange(0, h)),
                                                       self.TRANSPARENT_COLOR)
                segment.set_alpha(alpha)

    def update(self):
        if not self.is_playing():
            step = self.parent.phage_step * self.health
            self.t += step
            yr = self.yr
            for ii, segment in sorted(enumerate(self.body), key=lambda b: b[0],
                                      reverse=True):
                dx = self.parent.deviation.get_y(self.t - ii * step) * \
                     self.parent.stray * self.rail.get_modifier()
                segment.location.center = self.rail.x + dx, \
                                          yr[1] - (yr[1] - yr[0]) * (self.t - \
                                                                     step * ii)
                segment.update()
        else:
            for segment in self.body:
                segment.update()
        Animation.update(self)


class Oracle(Animation):

    def __init__(self, parent):
        Animation.__init__(self, parent)
        self.time_filter = self.get_game().time_filter
        self.display_surface = self.get_display_surface()
        # self.line_appears_fx = SoundEffect(self, "no")
        screens = self.screens = []
        for ii in xrange(2):
            surface = Surface((48, 48), SRCALPHA)
            surface.fill((127, 127, 127, 127))
            screens.append(surface)
        lines = self.lines = []
        for ii in xrange(2):
            line = Surface((36, 6))
            line.fill((31, 31, 31))
            if ii == 1:
                key = (255, 0, 255)
                line.set_colorkey(key)
                line.fill(key, (14, 0, 8, 6))
            lines.append(line)
        self.animals = Animals(self)
        self.coins = [Coin(self, ii) for ii in xrange(3)]
        self.register(self.display_indicator)
        self.clear()

    def display_indicator(self):
        self.clear_screens()
        self.parent.parent.book.hide_explanations()
        response = choice(self.parent.parent.book)
        response.show_indicator()
        response.show_explanation()
        response.explanation.halt()

    def clear_screens(self):
        for screen in self.screens:
            screen.fill(screen.get_at((0, 0)))

    def clear(self):
        self.hexagram = []
        self.flips = 0
        self.flip_elapsed = 0
        self.wait_elapsed = 0
        self.waiting = False
        self.clear_screens()
        for coin in self.coins:
            coin.hide()
        self.animals.hide()
        self.halt()

    def update(self):
        if not self.parent.is_frozen() and not self.waiting:
            if self.flips == 0:
                for coin in self.coins:
                    coin.unhide()
                    coin.set_frameset(0)
            if len(self.hexagram) == 6:
                self.clear()
                self.parent.parent.book.hide_indicators()
                for hexagram in self.parent.parent.book:
                    explanation = hexagram.explanation
                    if not explanation.is_hidden():
                        frameset = explanation.get_current_frameset()
                        frameset.current_index = frameset.length() - 1
                        hexagram.explanation.play()
                self.parent.increase_wave()
                self.flip_elapsed = 0
            else:
                flip_length = 1500
                self.flip_elapsed += self.time_filter.get_last_frame_duration()
                if self.flip_elapsed > flip_length:
                    self.coins[self.flips].end_flip()
                    self.flips += 1
                    self.flip_elapsed -= flip_length
                    if self.flips == 3:
                        self.hexagram.append(Result(self.coins))
                        if len(self.hexagram) == 3:
                            self.animals.send(self.hexagram)
                        elif len(self.hexagram) == 6:
                            self.play(self.display_indicator, delay=1000,
                                      play_once=True)
                        self.flips = 0
                        self.waiting = True
                        # self.line_appears_fx.play()
        elif self.waiting:
            self.wait_elapsed += self.time_filter.get_last_frame_duration()
            if self.wait_elapsed > 7500:
                self.waiting = False
                self.wait_elapsed = 0
        ow, oh = 32, 16
        if self.parent.parent.book.are_indicators_hidden():
            for ii, result in enumerate(self.hexagram):
                screen = self.screens[ii / 3]
                screen.blit(self.lines[result.get_line_index()],
                            (6, 5 + ((2 - ii) % 3) * 16))
        for ii, screen in enumerate(self.screens):
            rect = screen.get_rect()
            if ii == 0:
                rect.topleft = (ow, oh)
            else:
                rect.topright = self.display_surface.get_width() - ow, oh
            self.display_surface.blit(screen, rect)
        for coin in self.coins:
            coin.update()
        Animation.update(self)


class Animals(GameChild, list):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.collect_token_fx = SoundEffect(self, "power-up", .7)
        font = Font(self.get_resource("display", "font"), 18)
        color = Color(0, 0, 0)
        for glyph in [u"馬", u"羊", u"雉", u"龍", u"雞", u"豕", u"狗", u"牛"]:
            animal = Sprite(self, 80)
            for ii in xrange(3):
                hue = int(360 * float(ii) / 3)
                for jj in xrange(8):
                    lightness = 20 + 80 * float(jj + 1) / 8
                    w, h = font.size(glyph)
                    frame = Surface((w + 2, h + 2), SRCALPHA)
                    color.hsla = hue, 80, lightness, 100
                    frame.blit(font.render(glyph, True, color), (0, 0))
                    frame.blit(font.render(glyph, True, color), (1, 0))
                    frame.blit(font.render(glyph, True, color), (2, 0))
                    frame.blit(font.render(glyph, True, color), (2, 1))
                    frame.blit(font.render(glyph, True, color), (2, 2))
                    frame.blit(font.render(glyph, True, color), (1, 2))
                    frame.blit(font.render(glyph, True, color), (0, 2))
                    frame.blit(font.render(glyph, True, color), (0, 1))
                    color.hsla = (hue + 60) % 360, 100, lightness, 100
                    frame.blit(font.render(glyph, True, color), (1, 1))
                    animal.add_frame(frame)
            paddles = self.parent.parent.paddles
            animal.add_location(count=3)
            self.append(animal)
        self.hide()

    def hide(self):
        self.in_motion = None
        for animal in self:
            animal.hide()

    def send(self, hexagram):
        index = sum(2 ** ii * x for ii, x in \
                    enumerate(reversed([r.get_binary() for r in hexagram])))
        in_motion = self.in_motion = self[index]
        for location in in_motion.locations:
            location.bottom = self.parent.parent.link.background. \
                              location.bottom
        in_motion.unhide()

    def update(self):
        if self.in_motion:
            paddles = self.parent.parent.paddles
            for ii, location in enumerate(self.in_motion.locations):
                location.centerx = paddles.paddles.location.left + \
                                   paddles.paddle_length / 2
                if ii / 2:
                    location.centerx += self.get_display_surface().get_width()
                if ii % 2:
                    location.centerx += paddles.paddle_length + paddles.margin
            if self.in_motion.location.colliderect(paddles.paddles.location):
                paddles.arrange_graticules(self.index(self.in_motion) + 1)
                self.collect_token_fx.play(paddles.paddles.location.centerx / \
                                           float(self.get_display_surface().\
                                                 get_width()))
                self.hide()
            else:
                self.in_motion.move(dy=4)
                self.in_motion.update()


class Coin(Sprite):

    HEADS, TAILS = "heads", "tails"

    def __init__(self, parent, ii):
        Sprite.__init__(self, parent)
        key = (255, 0, 255)
        w = 8
        for frame_ii in xrange(w):
            frame = Surface((w, w))
            frame.fill(key)
            frame.set_colorkey(key)
            x = [0, 1, 2, 3, 3, 2, 1, 0][frame_ii]
            rect = (x, 0, (w / 2 - x) * 2, w)
            thickness = 0 if frame_ii < (w / 2) else 1
            ellipse(frame, (160, 120, 40), rect)
            ellipse(frame, (200, 150, 60), rect, thickness)
            self.add_frame(frame)
        self.add_frameset([0], name=self.HEADS)
        self.add_frameset([w - 1], name=self.TAILS)
        self.add_frameset(xrange(w), name="flipping")
        self.location.top = 36
        self.location.centerx = 20 * (ii - 3 / 2.0 + .5) + \
                                self.display_surface.get_rect().centerx
        self.hide()

    def end_flip(self):
        if randint(0, 1):
            self.side = self.HEADS
        else:
            self.side = self.TAILS
        self.set_frameset(self.side)


class Result:

    def __init__(self, coins):
        total = 0
        for coin in coins:
            if coin.side == coin.HEADS:
                total += 3
            else:
                total += 2
        self.total = total

    def get_line_index(self):
        return 0 if self.total in [7, 9] else 1

    def get_binary(self):
        return 0 if self.total in [7, 9] else 1
216.73.216.21
216.73.216.21
216.73.216.21
 
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 😇