from os import listdir
from os.path import isfile, join
from sys import exc_info, stdout
from glob import glob

from pygame import Color, Rect, Surface
from pygame.image import load
from pygame.transform import flip
from pygame.locals import *

from Animation import Animation
from Vector import Vector

class Sprite(Animation):

    def __init__(self, parent, framerate=None):
        Animation.__init__(self, parent, self.shift_frame, framerate)
        self.frames = []
        self.mirrored = False
        self.alpha = 255
        self.locations = []
        self.framesets = [Frameset(self, framerate=framerate)]
        self.motion_overflow = Vector()
        self.display_surface = self.get_display_surface()

    def __getattr__(self, name):
        if name in ("location", "rect"):
            return self.locations[0]
        if hasattr(Animation, "__getattr__"):
            return Animation.__getattr__(self, name)
        raise AttributeError, name

    def set_frameset(self, identifier):
        if isinstance(identifier, str):
            for ii, frameset in enumerate(self.framesets):
                if == identifier:
                    identifier = ii
        self.frameset_index = identifier
        if self.get_current_frameset().length() > 1:

    def register_interval(self):

    def get_current_frameset(self):
        return self.framesets[self.frameset_index]

    def update_location_size(self):
        size = self.get_current_frameset().rect.size
        for location in self.locations:
            location.size = size

    def set_framerate(self, framerate):

    def load_from_path(self, path, transparency=False, ppa=True, key=None,
                       query=None, omit=False):
        if isfile(path):
            paths = [path]
            if query:
                paths = sorted(glob(join(path, query)))
                paths = [join(path, name) for name in sorted(listdir(path))]
        for path in paths:
            img = load(path)
            if transparency:
                if ppa:
                    frame = img.convert_alpha()
                    frame = self.fill_colorkey(img, key)
                frame = img.convert()
            self.add_frame(frame, omit)

    def fill_colorkey(self, img, key=None):
        if not key:
            key = (255, 0, 255)
        img = img.convert_alpha()
        frame = Surface(img.get_size())
        frame.blit(img, (0, 0))
        return frame

    def add_frame(self, frame, omit=False):
        if not omit:
            frameset = self.get_current_frameset()
            if frameset.length() > 1:

    def shift_frame(self):

    def get_current_frame(self):
        return self.frames[self.get_current_frameset().get_current_id()]

    def move(self, dx=0, dy=0):
        for location in self.locations:
            location.move_ip(dx, dy)

    def reset_motion_overflow(self):
        for location in self.locations:

    def collide(self, other):
        if not isinstance(other, Rect):
            other = other.rect
        for location in self.locations:
            if location.colliderect(other):
                return location

    def mirror(self):
        frames = self.frames
        for ii, frame in enumerate(frames):
             frames[ii] = flip(frame, True, False)
        self.mirrored = not self.mirrored

    def clear_frames(self):
        self.frames = []
        for frameset in self.framesets:
            frameset.order = []

    def add_location(self, topleft=None, offset=(0, 0), count=1, base=0):
        if topleft is not None:
            for ii in xrange(count):
                    self, Rect(topleft, self.locations[0].size)))
            base = self.locations[base]
            current_offset = list(offset)
            for ii in xrange(count):
                current_offset[0] += offset[0]
                current_offset[1] += offset[1]
        return self.locations[-1]

    def fade(self, length=0, out=None, index=None):
        if index is None:
            for location in self.locations:
                location.fader.start(length, out)
            self.locations[index].fader.start(length, out)

    def set_alpha(self, alpha):
        self.alpha = alpha
        for frame in self.frames:
        for location in self.locations:

    def add_frameset(self, order=[], framerate=None, name=None, switch=False):
        frameset = Frameset(self, order, framerate, name)
        if switch:
            self.set_frameset(len(self.framesets) - 1)
        return frameset

    def hide(self):
        for location in self.locations:

    def unhide(self):
        for location in self.locations:

    def toggle_hidden(self):
        for location in self.locations:

    def is_hidden(self):
        return all(location.is_hidden() for location in self.locations)

    def remove_locations(self, location=None):
        if location:
            self.locations = self.locations[:1]

    def reverse(self, frameset=None):
        if frameset:
            for frameset in self.framesets:

    def update(self, areas=None, substitute=None):
        if self.get_current_frameset().length():
            self.draw(areas, substitute)

    def draw(self, areas=None, substitute=None):
        for location in self.locations:
            location.fader.draw(areas, substitute)

class Location(Rect):

    def __init__(self, sprite, rect=(0, 0, 0, 0)):
        self.sprite = sprite
        Rect.__init__(self, rect)
        self.motion_overflow = Vector()
        self.fader = Fader(self)

    def move_ip(self, dx, dy):
        if isinstance(dx, float) or isinstance(dy, float):
            excess = self.update_motion_overflow(dx, dy)
            Rect.move_ip(self, int(dx) + excess[0], int(dy) + excess[1])
            Rect.move_ip(self, dx, dy)

    def update_motion_overflow(self, dx, dy):
        overflow = self.motion_overflow
        overflow.move(dx - int(dx), dy - int(dy))
        excess = map(int, overflow)
        overflow[0] -= int(overflow[0])
        overflow[1] -= int(overflow[1])
        return excess

    def reset_motion_overflow(self):

    def apply_motion_overflow(self, coordinates=None):
        if coordinates is None:
            coordinates = self.topleft
        return self.motion_overflow + coordinates

    def hide(self):
        self.hidden = True

    def unhide(self):
        self.hidden = False

    def toggle_hidden(self):
        self.hidden = not self.hidden

    def is_hidden(self):
        return self.hidden

class Fader(Surface):

    def __init__(self, location):
        self.location = location
        self.time_filter = location.sprite.get_game().time_filter

    def reset(self):
        self.fade_remaining = None

    def init_surface(self):
        Surface.__init__(self, self.location.size)
        if self.location.sprite.get_current_frameset().length():
            background = Surface(self.get_size())
            sprite = self.location.sprite
            key = sprite.get_current_frame().get_colorkey() or (255, 0, 255)
            self.background = background

    def set_alpha(self, alpha=None):
        if alpha is None:
            alpha = self.location.sprite.alpha
        Surface.set_alpha(self, alpha)

    def start(self, length, out=None):
        if self.fade_remaining <= 0:
            alpha = self.get_alpha()
            maximum = self.location.sprite.alpha
            if out is None:
                out = alpha == maximum
            if out and alpha > 0 or not out and alpha < maximum:
                self.fade_length = self.fade_remaining = length
                self.start_time = self.time_filter.get_ticks()
                self.fading_out = out

    def draw(self, areas=None, substitute=None):
        sprite = self.location.sprite
        if substitute is None:
            frame = sprite.get_current_frame()
            frame = substitute
        if self.fade_remaining >= 0:
            self.blit(frame, (0, 0))
            if not self.location.is_hidden():
                self.blit_to_display(self, areas)
        elif self.fade_remaining is None or self.get_alpha() >= sprite.alpha:
            if self.fade_remaining >= 0:
            if not self.location.is_hidden():
                self.blit_to_display(frame, areas)

    def blit_to_display(self, frame, areas=None):
        if not isinstance(areas, list):
            areas = [areas]
        for area in areas:
            if area:
                dest = area.left + self.location.left, \
                dest = self.location
            self.location.sprite.display_surface.blit(frame, dest, area)

    def update_alpha(self):
        remaining = self.fade_remaining = self.fade_length - \
                    (self.time_filter.get_ticks() - self.start_time)
        ratio = self.fade_length and float(remaining) / self.fade_length
        if not self.fading_out:
            ratio = 1 - ratio
        maximum = self.location.sprite.alpha
        alpha = int(ratio * maximum)
        if alpha > maximum:
            alpha = maximum
        elif alpha < 0:
            alpha = 0

    def clear(self):
        self.blit(self.background, (0, 0))

class Frameset:

    def __init__(self, sprite, order=[], framerate=None, name=None):
        self.sprite = sprite = name
        self.reversed = False
        self.order = []
        self.rect = Rect(0, 0, 0, 0)

    def add_index(self, order):
        if isinstance(order, int):
            order = [order]
        self.order += order

    def set_framerate(self, framerate):
        self.framerate = framerate

    def reset(self):
        self.current_index = 0

    def get_current_id(self):
        return self.order[self.current_index]

    def measure_rect(self):
        max_width, max_height = 0, 0
        frames = self.sprite.frames
        for index in self.order:
            frame = frames[index]
            width, height = frame.get_size()
            max_width = max(width, max_width)
            max_height = max(height, max_height)
        self.rect.size = max_width, max_height

    def shift(self):
        if len(self.order) > 1:

    def increment_index(self, increment=None):
        if increment is None:
            increment = 1 if not self.reversed else -1
        index = self.current_index + increment
        while index < 0:
            index += self.length()
        while index >= self.length():
            index -= self.length()
        self.current_index = index

    def length(self):
        return len(self.order)

    def reverse(self):
        self.reversed = not self.reversed
June 23, 2019

is pikachu dead

yes and how about that for a brain tickler that what you're seeing all along was a ghost. we used a digital stream of bits that in the future we call blood to recreate everything as a malleable substance that is projected through computers over a massive interstellar network that runs faster than the speed of light in order to simultaneously exist at every moment in time exactly the same way effectively creating a new dimension through which you can experience the timeless joy of video games. you can press a button and watch the impact of your actions instantaneously resonate eternally across an infinite landscape as you the master of a constantly regenerating universe supplant your reality with your imagination giving profoundly new meaning to the phrase what goes around comes around as what comes around is the manifestation of the thoughts you had before you were aware of them. thoughts before they were thought and actions before they were done! it's so revolutionary we saved it for 10,000 years from now but its all recycled here in the past with you at the helm and the future at the tips of your fingers

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!

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.

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!