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
54.162.227.37
54.162.227.37
54.162.227.37
 
June 7, 2018

May 17, 2018

Line Wobbler Advance is a demake of Line Wobbler for Game Boy Advance that started as a demo for Synchrony. It contains remakes of the original Line Wobbler levels and adds a challenging advance mode with levels made by various designers.


f1. Wobble at home or on-the-go with Line Wobbler Advance

This project was originally meant to be a port of Line Wobbler and kind of a joke (demaking a game made for even lower level hardware), but once the original levels were complete, a few elements were added, including a timer, different line styles and new core mechanics, such as reactive A.I.


f2. Notes on Line Wobbler

I reverse engineered the game by mapping the LED strip on paper and taking notes on each level. Many elements of the game are perfectly translated, such as enemy and lava positions and speeds and the sizes of the streams. The boss spawns enemies at precisely the same rate in both versions. Thanks in part to this effort, Line Wobbler Advance was awarded first prize in the Wild category at Synchrony.


f3. First prize at Synchrony

Advance mode is a series of levels by different designers implementing their visions of the Line Wobbler universe. This is the part of the game that got the most attention. It turned into a twitchy gauntlet filled with variations on the core mechanics, cinematic interludes and new elements, such as enemies that react to the character's movements. Most of the levels are much harder than the originals and require a lot of retries.

Thanks Robin Baumgarten for giving permission to make custom levels and share this project, and thanks to the advance mode designers Prashast Thapan, Charles Huang, John Rhee, Lillyan Ling, GJ Lee, Emily Koonce, Yuxin Gao, Brian Chung, Paloma Dawkins, Gus Boehling, Dennis Carr, Shuichi Aizawa, Blake Andrews and mushbuh!

DOWNLOAD ROM
You will need an emulator to play. Try Mednafen (Windows/Linux) or Boycott Advance (OS X)

September 26, 2017

I made a video about my game Picture Processing for Out of Index 2017! Here is the video along with a transcript.

To save memory, video games are designed to repeat graphics. In raster-based games, image files like textures, tiles and sprites are loaded once into memory and drawn repeatedly by the program to create environments, characters, animations and text. In my puzzle game, 8 by 8 pixel tiles are used to create scenes the player has to recreate. For level 1, the tiles are a cloud, a tree, a mushroom, a character, sky, ground and rock.

An algorithm scrambles the tiles so that each tile is in the wrong memory address at the beginning of a level and the screen looks like a graphics glitch. When level 1 begins, the clouds may be where the trees should be, the mushrooms may be floating in the sky and the character may be switched with rock or the ground. The player's task is to put the tiles where they belong by swapping each tile with a tile in another memory address.

There are five levels, in order of difficulty, based on classic video games or classic video game genres.

The name of this game is taken from the Picture Processing Unit, a microprocessor designed by Nintendo for the Nintendo Entertainment System. The PPU is the hardware component responsible for translating image data into video signals for televisions and screens. It does this with a memory of 8 by 8 pixel tile data, which, along with palette and sprite attribute memory, generates each frame of a video game.

Companies often create lofty, evocative titles for hardware and products. What does the name Picture Processing Unit mean if we consider pictures something independent of a video screen? The phrase picture processing evokes the phrase image processing, a technique used to create applications such as automatic facial and emotion recognition. We often anthropomorphize electronic devices, infusing them with intelligence and souls, forgetting how much more infinitely complex the human mind is compared to a digital processor.

The game is named as a reference to Nintendo's microprocessor because the graphics are tile based, but it is also a reference to the players who are image processors, interpreting a picture from something deterministic into something non-deterministic.

The prototype of this game was created for a game jam called A Game By Its Cover where designers created video games based on imagined Nintendo game cartridges created by visual artists for an exhibition called My Famicase.

Picture Processing is based on one of the imagined cartridges from that exhibition. The cartridge's cover depicts a grid of unordered tiles and is described as a game where one inserts a game cartridge, sees a glitching screen, and meditates about the concept of beauty in imperfection. I added the idea that the player meditates into a state of transcendence until they are able to fix the game's graphics by accessing the memory telepathically.

July 19, 2017


f1. BOSS

Games are corrupt dissolutions of nature modeled on prison, ordering a census from the shadows of a vile casino, splintered into shattered glass, pushing symbols, rusted, stale, charred, ultraviolet harbingers of consumption and violence, badges without merit that host a disease of destruction and decay.

You are trapped. You are so trapped your only recourse of action is to imagine an escape route and deny your existence so fully that your dream world becomes the only reality you know. You are fleeing deeper and deeper into a chasm of self-delusion.

While you're dragging your listless, distending corpus from one cell to another, amassing rewards, upgrades, bonuses, achievements, prizes, add-ons and status boosts in rapid succession, stop to think about what's inside the boxes because each one contains a vacuous, soul-sucking nightmare.

Playing can be an awful experience that spirals one into a void of harm and chaos, one so bad it creates a cycle between the greater and lesser systems, each breaking the other's rules. One may succeed by acting in a way that ruins the world.

June 5, 2016
September 30, 2015


Edge of Life is a form I made with Babycastles and Mouth Arcade for an event in New York called Internet Yami-ichi, a flea market of internet-ish goods. We set up our table to look like a doctor's office and pharmacy and offered free examinations and medication prescriptions, a system described by one person as "a whole pharmacy and medical industrial complex".

Diagnoses were based on responses to the form and observations by our doctor during a short examination. The examination typically involved bizarre questions, toy torpedoes being thrown at people and a plastic bucket over the patient's head. The form combined ideas from Myers-Briggs Type Indicators, Codex Seraphinianus and chain-mail personality tests that tell you which TV show character you are. In our waiting room, we had Lake of Roaches installed in a stuffed bat (GIRP bat). It was really fun!

The icons for the food pyramid are from Maple Story and the gun icons are from the dingbat font Outgunned. I'm also using Outgunned to generate the items in Food Spring.

January 28, 2014


E F F L U E N C E

December 3, 2013

Where in the mind's prism does light shine, inward, outward, or backward, and where in a plane does it intersect, experientially and literally, while possessing itself in a dripping wet phantasm?


Fig 1.1 What happens after you turn on a video game and before it appears?

The taxonomy of fun contains the difference between gasps of desperation and exaltation, simultaneously identical and opposite; one inspires you to have sex, while the other to ejaculate perpetually. A destruction and its procession are effervescent, while free play is an inseminated shimmer hatching inside you. Unlikely to be resolved, however, in such a way, are the climaxes of transitions between isolated, consecutive game states.

You walk through a door or long-jump face first (your face, not Mario's) into a painting. A moment passes for eternity, viscerally fading from your ego, corpus, chakra, gaia, the basis of your soul. It happens when you kill too, and especially when you precisely maim or obliterate something. It's a reason to live, a replicating stasis.


Fig 1.2 Sequence in a video game

Video games are death reanimated. You recurse through the underworld toward an illusion. Everything in a decision and logic attaches permanently to your fingerprint. At the core, you use its energy to soar, comatose, back into the biosphere, possibly because the formal structure of a mind by human standards is useful in the next world.

November 9, 2013


Food Spring - Watermelon Stage

Getting the fruit as far as possible is the object of each level, collecting bigger, more valuable guns. The final result is determined by the size of the fruits' collection when the monkey arrives in North America and either survives or perishes in the fruits' attack.

Watermelon Peach
Pineapple Grapes
September 13, 2013

from array import array
from time import sleep

import pygame
from pygame.mixer import Sound, get_init, pre_init

class Note(Sound):

    def __init__(self, frequency, volume=.1):
        self.frequency = frequency
        Sound.__init__(self, self.build_samples())
        self.set_volume(volume)

    def build_samples(self):
        period = int(round(get_init()[0] / self.frequency))
        samples = array("h", [0] * period)
        amplitude = 2 ** (abs(get_init()[1]) - 1) - 1
        for time in xrange(period):
            if time < period / 2:
                samples[time] = amplitude
            else:
                samples[time] = -amplitude
        return samples

if __name__ == "__main__":
    pre_init(44100, -16, 1, 1024)
    pygame.init()
    Note(440).play(-1)
    sleep(5)

This program generates and plays a 440 Hz tone for 5 seconds. It can be extended to generate the spectrum of notes with a frequency table or the frequency formula. Because the rewards in Send are idealized ocean waves, they can also be represented as tones. Each level has a tone in its goal and a tone based on where the player's disc lands. Both play at the end of a level, sounding harmonic for a close shot and discordant for a near miss. The game can dynamically create these tones using the program as a basis.

I'm also building an algorithmically generated song: Silk Routes (Scissored). Here is an example of how it sounds so far:

August 12, 2013

I've been researching tartan/plaid recently for decoration in my updated version of Ball & Cup, now called Send. I want to create the atmosphere of a sports event, so I plan on drawing tartan patterns at the vertical edges of the screen as backgrounds for areas where spectator ants generate based on player performance. I figured I would make my own patterns, but after browsing tartans available in the official register, I decided to use existing ones instead.

I made a list of the tartans that had what I thought were interesting titles and chose 30 to base the game's levels on. I sequenced them, using their titles to form a loose narrative related to the concept of sending. Here are three tartans in the sequence (levels 6, 7 and 8) generated by an algorithm I inferred by looking at examples that reads a tartan specification and draws its pattern using a simple dithering technique to blend the color stripes.


Acadia


Eve


Spice Apple

It would be wasting an opportunity if I didn't animate the tartans, so I'm thinking about animations for them. One effect I want to try is making them look like water washing over the area where the ants are spectating. I've also recorded some music for the game. Here are the loops for the game over and high scores screens.

Game Over

High Scores

June 29, 2013

A few weeks ago, for Fishing Jam, I made a fishing simulation from what was originally designed to be a time attack arcade game. In the program, Dark Stew, the player controls Aphids, an anthropod who fishes for aquatic creatures living in nine pools of black water.



Fishing means waiting by the pool with the line in. The longer you wait before pulling the line out, the more likely a creature will appear. Aside from walking, it's the only interaction in the game. The creatures are drawings of things you maybe could find underwater in a dream.

The background music is a mix of clips from licensed to share songs on the Free Music Archive. Particularly, Seed64 is an album I used a lot of songs from. The full list of music credits is in the game's README file.

I'm still planning to use the original design in a future version. There would be a reaction-based mini game for catching fish, and the goal would be to catch as many fish as possible within the time limit. I also want to add details and obstacles to the background, which is now a little boring, being a plain, tiled, white floor.

If you want to look at all the drawings or hear the music in the context of the program, there are Windows and source versions available. The source should work on any system with Python and Pygame. If it doesn't, bug reports are much appreciated. Comments are also welcome :)

Dark Stew: Windows, Pygame Source

I wrote in my last post that I would be working on an old prototype about searching a cloud for organisms for Fishing Jam. I decided to wait a while before developing that game, tentatively titled Xenographic Barrier. Its main interactive element is a first-person scope/flashlight, so I'd like to make a Wii version of it.

I'm about to start working on a complete version of Ball & Cup. If I make anything interesting for it, I'll post something. There are a lot of other things I want to write about, like game analyses, my new GP2X and arcades in Korea, and there's still music to release. Lots of fun stuff coming!

May 19, 2013

Welcome! I will be posting here about open-source games and music I am making for free online distribution. Most recently, I made Ball & Cup for Ludum Dare 26, a game I will work on more in June. After finishing, if it's fun, I will build an arcade cabinet for it! Next week, I am joining the 7-Day Fishing Jam to develop an A-life prototype about searching a cloud of noise for organisms.

Before Ball & Cup, I was adding features like vehicle engines, new graphics and effects and detailed scoring to an updated version of E.S.P. Hadouken, currently a prototype about navigating five psychic hadoukens to save your Game Boy. The new version will be similar with a clearer story and more ways to judge your performance. I plan on finishing it after making a public version of Ball & Cup.

I will also upload some digital albums soon. One, Man's Womb, is a solo collection of chiptunes from Emoticon Vs. Rainbow, an online racing/rhythm game. The other, Tor Ghul/Spin Ghul is a guitar and synth record recorded with my friends last summer. The recording and sequencing are finished for both -- I just have to make their web pages and artwork and package them for downloading.

Later, I hope to write about games in their early stages, an abstract action-RPG called Panopticon: Swarm, a massively multiplayer exploration, voting, post-catastrophic city simulation, Vomit Inspector and a mobile mini-game compilation project that includes an external digital pet raising and social networking mode. I also plan to post analyses of games I'm playing as a design exercise and for fun.

I will write about more game stuff like arcade trips, game jams and electronics! Plus whatever I haven't thought of! If you use RSS, subscribe to my feed!


↠ RSS Feed ↞