Simple Recursive Maze

July 26th, 2010

Here is a simple recursive maze generator I wrote to help a friend learn a little more about how recursion works. I figured I’d post it here as well.

#! /usr/bin/env python

import random

# Width and height of maze needs to be an even number because of walls
WIDTH = 60
HEIGHT = 20

# The change in x and y for all four directions
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)

def recursive_maze(maze, x=0, y=0, dirx=0, diry=0):
	# Check if current position is inside maze boundry
    if 0 <= y < len(maze):
        if 0 <= x < len(maze[0]):
			# Check if this position can have a new hallway going to it
            if maze[y][x] == "#":
				# Make this position into a hallway
                maze[y][x] = " "

                # Connect this position with previous position
                maze[y-diry][x-dirx] = " "

                # Create direction list and randomize it's order
                directions = [UP, DOWN, LEFT, RIGHT]
                random.shuffle(directions)

                # Follows each direction when the callstack returns here
                for dx, dy in directions:
					# Go down this current direction
                    recursive_maze(maze, x + dx*2, y + dy*2, dx, dy)

def draw_maze(maze):
	# Draw top wall
    print "#" * (len(maze[0])+1)
    # Draw each line with left wall added in
    for line in maze:
        print "#" + "".join(line)

# Initialize the maze as am array of arrays filled with wall spaces
maze = [["#" for j in xrange(WIDTH)] for i in xrange(HEIGHT)]

# Start making the maze
recursive_maze(maze)

# Finally, draw it
draw_maze(maze)

The output of this program will look similar to this:

#############################################################
# #       #     #           #           #               #   #
# ##### # # ### # ######### ####### ### # ########### # # ###
#   #   # #   # #   #     #   #   # # # # #           # #   #
### # ### ### # ### ### # ### # # # # # ### ########### ### #
#   #   #     #   # #   # #   # #   # #   # #     #   # #   #
# ##### ######### # # ### # ### ##### ### # # ### # # # # ###
# #     # #     #   #   # # #   #     #   #     # # # # #   #
# # ##### # # ######### ### # ### ### # ######### # ### ### #
# # #       #         #   #   #     # #         # # #   #   #
# # ### ########### # ### ######### ########### # # # ### ###
# #   #   #       # #     #         #           # # # #     #
# # # ### # ####### ####### ### ### # ########### # # # ### #
# # # # #   #       #     #   #   # # #           # # # #   #
# # # # # ### ##### # ### ### ### ### ########### # # ### # #
# # # #   #   #     # # #     #   #   #         # #   #   # #
# ### # ### ##### ### # ####### ### ### ####### # # ### ### #
# #   # # # #   # #   #       #     #   #     #   #     #   #
# # ### # # # # ### ####### # ######### # ### ########### ###
#   #     #   #             #           #   #               #
#############################################################

Python Message Queues and Publishers

March 5th, 2010

PyWeek is approaching, so I’ve decided that I will post some cut-and-paste code to hopefully make the process of game development quicker and easier.  Usually I end up needing to rewrite basically the same code over and over again and spend most of the first two days of any competition just implementing basic features.

This first article will feature message queue and publisher classes.  They are quite simple, yet certainly useful.

Message Queue

The message queue class is very short and simple.

class MsgQueue:
    def __init__(self):
        self.messages = []

    def post(self, msg, category, *args):
        self.messages.append((msg, category, args))

    def get(self):
        for msg in self.messages:
            yield msg
        self.messages = []

Messages can be posted to it and retrieved from it through the ‘post’ and ‘get’ functions.  The messages that are posted are tuples of message, category, and arguments.  The categories can be used to group messages of similar types together.  For example, in a game there might be a category called ‘switches,’ where a message is posted each time a switch in the level is turned on or off.

The ‘get’ function is a generator for iterating through the messages then clearing the list of messages.

#Example Use for MsgQueue
q = MsgQueue()
q.post("red switch on", "switches")
q.post("red switch off", "switches", "with an extra argument")

# elsewhere in a sea of code ...

for msg,category,args in q.get():
    if category == "switches":
        if msg == "red switch on":
            fire_laser_beams("Pew! Pew!")
        elif msg == "red switch off":
            stop_firing_those_lasers()

Publisher With Message Queues Subscribers

Message queues can subscribe to message categories within this message publisher class.

class MsgPublisher:
    def __init__(self):
        self.categories = {}

    def subscribe(self, subscriber, category='default'):
        if not self.categories.has_key(category):
            self.categories[category] = []

        self.categories[category].append(subscriber)

    def unsubscribe(self, subscriber, category = None):
        if category is None:
            for c in self.categories.itervalues():
                c.remove(subscriber)

        else:
            if self.categories.has_key(category):
                self.categories[category].remove(subscriber)

    def post(self, msg, category='default', *args):
        if self.categories.has_key(category):
            for subscription in self.categories[category]:
                subscription.post(msg, category, *args)

The method ‘subscribe’ is used to subscribe a message queue to a publisher.  Categories are used to group subscriptions so that a single publisher can serve several uses.  A subscribing message queue will need to subscribe to each of these categories separately. If category is blank ‘default’ will be used.

The method ‘unsubscribe’ removes a subscribed message queue from it’s subscription list(s).  If category is ‘None’ (default) it will be unsubscribed from all of the categories.

The method ‘post’ is used for posting messages to the subscribed message queues.  Each message will be sent to all of the message queues that have subscribed to the specified category.

#Example use of MsgPublisher
qa = MsgQueue()
qb = MsgQueue()
qc = MsgQueue()

p = MsgPublisher()
p.subscribe(qa)
p.subscribe(qb)
p.subscribe(qb, "new category")
p.subscribe(qc, "new category")

p.post("message")  # sent to qa and qb
p.post("something else", "new category")  # sent to qb and qc

p.unsubscribe(qa)
p.unsubscribe(qb, "new category")  # qb will be removed from "new category"
p.unsubscribe(qb)  # now qb removed from all categories
p.unsubscribe(qc)  # will be removed from all categories

Opportunities for Use

There are many times when speed and direct interaction are not needed but flexibility is.  In a game objects can simply plug in and listen to the messages being sent — creating an easy and modular system.  Also it is more like asking for things to happen than telling other parts of your program to do things.  These messages can be ignored.

Some instances where message queues and publishers might be useful include: game state changes, abstraction to other systems such as sound, world dynamics, communications between game entities, etc.

PIRATE KART II: KLIK HARDER

March 5th, 2010

I had a lot of fun making four simple games for the THE 371-IN-1 KLIK & PLAY PIRATE KART II: KLIK HARDER.  It was basically a challenge to see if a bunch of random people could make at least 371 games over the February 27-28 weekend.  We succeeded and then some!  106 people contributed and 529 games were made.

Most of the simply used graphics and sounds stolen from other sources, but I decided to make custom content for all my games.  My favourite is Rolling Hills, which even has music!

My four games can be found at here. Have fun!

Random Neighborhood Generator

January 20th, 2009
Random Neighborhood Generator

Random Neighborhood Generator

I was wondering how visually interesting a randomly generated neighborhood could be a made by using simple binary subdivision.  Basically the algorithm starts with a square, cuts it in half, cuts those halves in half, and so on to produce streets and plots of land.

It is in no way how a real neighborhood would be laid out, but for such simplicity I am rather satisfied with the results.  Such a system could randomly produce results that are visually interesting enough for possibly a small, simple flying or driving based game — such as having to rush a firetruck to burning homes, for example.

Here is the source code: neighborhood.py

Towlr

January 20th, 2009
You Can't Have Your Towlr And Eat It Too

You Can't Have Your Towlr And Eat It Too

A bunch of people at a game development competition site was putting together short confusing games they called “Towlrs.”  The intent of a Towlr is to leave the player wondering, “What exactly am I suppose to do to beat this game?”  I decided to get in on the action.

You Can’t Have Your Towlr And Eat It Too was my attempt at a Towlr.  It may be considerably easier than many of the other Towlrs, but the concept is somewhat interesting.

You can download it at the Towlr website (which includes a Windows executable), or you can go to the page I quickly thrown up on my site (Which requires Python and Pygame because I’m too lazy to copy the compiled vesion to my site.  Also, in the future I may move this to a different directory on my site, so be warned!)

Various Python Experiments

November 6th, 2008

Every so often I decide to write simple test programs in Python just for the fun of it.  Here are a few that I had written over in the past.  Please note, because these were originally just simple experiments the source code could be a little messy and poorly optimized in most of them.  Also note, these are not meant to be all that impressive.

All of the programs require Python and PIL (The Python Imaging Library.)

Simple Recursive Maze Generator

Simple Recursive Maze Generator

Simple Recursive Maze Generator

This is just a simple maze generator that uses a recursive function.  It creates a near-infinite number of random mazes.

Source: maze.py

Rectangle Packing

Rectangle Packing

Rectangle Packing

I wanted to figure out a simple and effective way of packing rectangle images in an OpenGL texture — which is useful for hardware accelerated 2D graphics.  The solution I came up with simply subdivides the availible free space and packs the rectangles from largest to smallest.  It may not produce the best packing results and there are quite a few wasted cycles in this implimentation, but, for being as simple as it is, it produces fairly reasonable results rather quickly.

Source: rect_packing.py

Simple Error Diffused Dithering

Error Diffuse Dithering

Error Diffuse Dithering

Just simple error diffusion based image dithering.  The above image is showing four color dithering.

Source: dither_test.py

Random Forest Path

Random Paths Through a Forest

Random Paths Through a Forest

I decided to try to see if I could easily produce a visual effect resembling erosion patterns in a forest area.  This was part of some preliminary work in trying to write a game that randomly generates a completely different world each time it’s played.  The results were very satisfying considering how simple the solution is.  Essentially it’s just squiggly lines of varying thickness with some textureing applied to it.

Source: forest_path.py

Image Outlining

Outlining an Image

Originally I wanted to see if I could have interesting features of an image identified and later used in some sort of image recoginition system.  Hilighting sharp edges brought out too many points to practically be used for comparing spacial relationships and proportions, but it did produce some nice results for drawing outlines on an image.

I wanted to test it on a picture of a person, so I found the above image online.  It is actually a composit of 32 american male faces averaged together.  I hope the creators of the website he’s from does’t mind.

Source: img_outline.py

MiniLD #2 – The Wizard

October 24th, 2008

MiniLD#2 - The Wizard

Way back in July I wrote this simplified Super Mario Brothers 3 game for the Mini Ludum Dare (a 48 hour mini-competition) that month.  The theme of the competition was a game based on a movie.  The movie that I picked was “The Wizard,” which is a movie about some kids who hitchhike across several states playing Nintendo games — so this would have been a video game about a movie about video games.

Originally I was going to have elements from Teenage Mutant Ninja Turtles and Double Dragon (both also featured in the movie) all tied together with an arcade style game where you control Jimmy and play these mini-games against people.  I figured if I made the Super Mario Brothers 3 part (which is the final showdown against Lucas) then I could easily adapt that to make the other parts.

All-in-all it was a little over ambitious, but I think I could have possibly pulled it off if I actually had two full days.  That saturday I went to watch a movie with friends, so I really only had one of the two days to work with.  I am, however, still very satisified with how much was accomplished in such a short amount of time.

Arrow Keys makes mario run, ‘x’ key makes him jump.

Download “The Wizard – The Game.”

Requires Python and PyGame.