Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Sunday, March 14, 2010

InstaPyGame progress report

I spent the last three days working on a prototype "space shooter" module for my InstaPyGame framework. I had hoped to have a prototype ready today, but the framework isn't usable yet. You can see my progress so far at my Google Code repository, but be warned; the code is messy and inconsistent, and nothing is set in stone.

However, I have created an API with which I'm satisfied. Making the sample below work properly is my goal for this prototype.


from insta.spaceshooter import *

def startDemo():

    game = Game(640, 480)
    
    player = Player()
    player.setSprite('resources/ship.gif')
    
    player.when(player.moving, 'left').setSprite('resources/bankingleft.gif')
    player.when(player.moving, 'right').setSprite('resources/bankingright.gif')
    
    shot = Shot()
    shot.setSprite('resources/shot.gif')
    
    player.setAmmo(shot)
    
    enemy = Enemy()
    enemy.setSprite('resources/alien.gif')
    
    boss = Enemy()
    boss.setSprite('resources/angryalien.gif')
    
    mapGen = LevelMapGenerator({'0' : None, '1' : player, '2' : enemy, '3' : boss})
    
    level = Level(mapGen.generate('data/levelmap1.txt'))
    level.setBGSprite('resources/space.gif')
    level.setBGMusic('resources/spacemusic.ogg')
    
    game.setLevels([level])
    game.start()

if __name__ == '__main__':

    startDemo()

Right now, I'm working on the event system and the controls, but the event system appears far more challenging. I'm planning to encapsulate the data for the "Player" and "Enemy" objects within another object, protecting the data behind its member functions. This should allow me to create a special data object that will apply its changes only when a condition is fulfilled.

Although the framework is far from complete, I'm excited about the possibilities. I have plenty of work ahead of me, but I think my goal is worth the effort.

Sunday, March 7, 2010

GSoC project idea: Insta-PyGame

I'm still trying to choose new GSoC organizations to join, but I know one of the organizations to which I'll apply: PyGame, the SDL-based Python multimedia library. I plan to write a micro-framework on top of PyGame to dramatically simplify the creation of conventional games.

The Problem

PyGame is a wrapper for the C SDL library. Some of the library hides the complexity of the underlying SDL library, but in most areas, PyGame is simply a Python binding for SDL. For that reason, you often need to write several lines of code to accomplish a simple task, such as checking whether the user has pressed a button. In addition, many pieces of the API are based on C coding idioms that are unfamiliar to most Python programmers.

The Plan

I propose the development of a new framework on to of PyGame that operates at a much higher level of abstraction. Through this new framework, people would create games by declaring the sprites the characters use, the arrangement and graphics of the levels, and the interactions between the player and the contents of the levels.

The framework would be divided into modules with each module representing a genre. The "platformer" module would contain everything necessary to create a platformer game, including a physics engine, a tile map engine, and enemies that die when you jump on them. In contrast, the "scrolling shooter" module would contain tools for controlling the behavior of projectiles and enemy ships.

Here's an example of the type of code games using the framework could look like. I haven't put much thought into the API, but I would like game code to be written at this level of abstraction.


from insta.menu import *

from insta.platformer import *



def startMenu():

    titleScreen = Screen(600, 400)
    titleScreen.setTheme(themes.MEDIEVAL)
    titleScreen.setTitle("Porcupine's Tiny Adventure")
    titleScreen.setOptions(["Play", "Controls", "Credits"])
    titleScreen.getOption("Play").setAction(startGame)
    # More code for other menu options

def startGame():

    game = Game()

    hero = Player()
    hero.setSprite("standing.gif")
    hero.setRunningSprites(["running1.gif", "running2.gif", "running3.gif"])
    hero.setJumpSprite("jumping.gif")
    hero.setDeathSprite("gravestone.gif")

    hero.setMovementTriggers(constants.ARROW_KEYS)
    hero.setJumpTrigger(constants.SPACE_BAR)

    goal = Item()
    goal.setSprite("bigring.gif")
    goal.setBehavior(constants.FLOATING)
    goal.setAction(game.nextLevel)

    itemGenerator = ItemGenerator([None, goal, hero])

    '''
    Tile generator translates level maps (text files full of numbers) into tile
    maps in a context-sensitive manner
    '''
    tileGenerator = TileGenerator()
    tileGenerator.setFloorSprite("levelground.gif")
    tileGenerator.setUndergroundSprite("underground.gif")
    tileGenerator.setPlatformSprite("platform.gif")
    # Edge and corner sprites could also be set

    mushroom = Enemy()
    mushroom.setRunningSprites(["step1.gif", "step2.gif"])
    mushroom.setDeathSprite("explosion.gif")
    # Some simple behaviors would be pre-defined
    mushroom.setBehavior(constants.WALKING)

    bird = Enemy()
    bird.setFlightSprites(["flap1.gif", "flap2.gif"])
    bird.setDeathSprite("feathers.gif")
    bird.setBehavior(constants.FLYING)

    # List associates enemy types with numbers in the text file
    enemyGenerator = EnemyGenerator([None, mushroom, bird])

    level = Level()
    level.setTileMap(tileGenerator.generateTileMap("levelmap1.txt"))
    level.setEnemyMap(enemyGenerator.generateEnemyMap("enemymap1.txt"))
    level.setItemMap(itemGenerator.generateItemMap("itemmap1.txt"))

    level.setBackground("background.gif")
    level.setBackgroundOptions([constants.TILED, constants.PARALLAX])

    game.setLevels([level])
    game.start()

if (__name__ == "__main__"):

    startMenu()

The Goal

I want to free PyGame developers from thinking about the hows of game development, allowing them to focus on the whats of their ideas. By freeing game creators from thinking about the implementation of their games, I hope to allow them to explore new ideas in video game design, such as dynamically-generated levels, media mashups, user-created content, and AI.

This is just a rough outline of the framework I'd like to build and the effects I hope to see. I plan to start work on a prototype soon if the PyGame community appears receptive to my idea.

Friday, August 21, 2009

Help people regain speech

Every year, thousands of people around the world lose their ability to speak. Some are struck dumb by strokes, while others' voices are stolen by degenerative diseases such as ALS or muscular dystrophy. These people can regain their ability to communicate by using speech augmentation software or devices to speak for them. Unfortunately, the obscene prices of both the software and hardware prevent many people from communicating.

I want to solve this problem by developing an open-source speech-augmentation program. My goal is to create a cross-platform speaking program with both a symbol-based and text-based interface. I plan to write the program in Python with an emphasis on flexibility and extensibility. I plan to abstract both the input and output interfaces, allowing the program to be independent of both its text-to-speech engine and its GUI framework.

Consider this post a project announcement and a call to action. If you'd like to help people regain the ability to speak and you have experience with Python, interface design, text-to-speech, or accessibility, send me an email. I need all the help I can get.

Thursday, August 20, 2009

Pygame2 example game finished

Early this summer, when my Google Summer of Code proposal to the Pygame project was rejected, I told the coordinator that I would nonetheless contribute to the project over the summer. I planned on writing examples and tutorials for the Pygame2 multimedia library. Unfortunately, events conspired to prevent me from writing the examples. I had tremendous difficulty installing Pygame2 properly and no time to find the problems: I finally overcame my installation problems only two weeks ago.

Composite screenshot of all four skins Four graphical skins for your gaming pleasure!

However, I spent a great deal of time over the last week writing my first example for Pygame2. It's based on the oldalien.py demo distributed with the original Pygame, but I greatly expanded its scope. I tried to demonstrate as much of the library as I could, but I ended up using only a sliver of the library's functionality. The finished example demonstrates Surface handling, vector drawing with pygame2.sdlext.draw, text rendering with pygame2.sdlttf, image loading with pygame2.sdlimage, and sound effects with pygame2.sdlmixer. It's not an exhaustive demonstration of those concepts, but I think it's a good starting point for exploration of the library.

In addition to showing off the Pygame2 library, I tried to demonstrate best practices. I encapsulated the object instantiation and sprite drawing in external factories, allowing users with incomplete installations of Pygame2 to still see parts of the example. I only have to switch factories to drastically change the look of the game. Most importantly, I expunged the global variables from all the classes. The game still uses a couple long-life variables, but I eliminated the unnecessary ones.

If you'd like to see my uber-example in action, you can get it from its SVN repository or download it as a .tar.gz archive. If you have any trouble with the game, let me know.

Sunday, May 10, 2009

Failed to build these modules: binascii zlib

It's very rare that I encounter a computer problem that I can't solve. I thrive on the challenge of rooting out the cause of an obscure error and finally getting my software to run properly. However, I thought I had been defeated by the error in the title of this post.

The trouble started when I tried to install Django on my Ubuntu Intrepid Ibex partition. I was unaware of the convenient apt-get method of installation, so I was going through Django's long list of dependencies, trying to find the initial critical library on which the entire list depended. I thought I had reached the end of the chain with Flup, a WSGI (Web Server Gateway Interface) library for Python. I tried to install it from its Python egg, but it threw several serious errors that indicated that I didn't have the necessary library to "hatch" the egg.

Of course, I found the required library and downloaded it, only to realize that it, too, was contained within a Python egg. The readme file clearly indicated that I could install the software by running a simple command: python [I forgot the name of the file].egg. Every time I tried, it would tell me that zlib wasn't installed and quit.

Of course, I looked up the "missing zlib" error and found some possible solutions. I tried to install the zlib python module from source and tried to download it from the repositories, but nothing would stop the fatal error.

I gave up.

Because my school work started to pick up, I didn't really have time to think about Ubuntu and my installation woes for about a month. The trouble started again as I was preparing for one of my Google Summer of Code proposals. When I attempted to install PGReloaded, an unstable development branch of the PyGame multimedia library, on my Intrepid Ibex partition, I encountered strange error after strange error, and I was completely unable to install the library. I thought that the problem might be related to my installation-from-source procedure, so I tried to install the standard Pygame library through apt-get and play a game that relied on it. The game couldn't find Pygame, even though I had just installed it.

I then remembered that installing Python 2.6 had given me an installation error: "Failed to build these modules: binascii zlib." I realized all my problems were caused by a faulty Python installation. First, I tried to verify the integrity of my Python installation. I checked md5 sums, ran tests, and reinstalled Python 2.6 from source. All the tests failed due to the absence of binascii and zlib. Looking for a fix, I started googling around, this time for Python installation message.

I found only one other instance of my problem in a post on a mailing list; unfortunately, the poster didn't get an answer. I thought that the gurus on the Python Help mailing list might be able to diagnose my problem and find a solution. Unfortunately, I hit a dead end there, too.

Now, the narrative flies off the tracks. If you want to read the whole convoluted tale and you have a taste for debugging narratives, you can take a look at Jaunty Jackalope released: Vista all over again. To summarize, I had to reinstall Intrepid Ibex and destroy all my files after an ill-advised "upgrade" to Jaunty Jackalope. I had to start from scratch.

Researching an entirely different problem, I stumbled across this Python 2.6 on Intrepid Ibex installation guide. Apparently, all my problems were caused by a conflict between the system default Python installation, 2.5, and the newer version, 2.6. I was thrilled to finally have my answer, but I wasn't looking forward to another lengthy, complex Python installation.

In the end, after a little advice from some python gurus, I decided to skip Python 2.6 entirely and stick with good ol' 2.5. This time, PGReloaded installed easily (for an unstable development library), and I don't expect any problems installing Django. I guess the moral of this story is "If a task becomes incredibly difficult, make sure that it's actually worth your time."

Saturday, January 10, 2009

Python Impressions

Why on earth would you care what I think about Python? I mean, really, what can I say about it that someone else hasn't? I'm not the most experienced programmer, so I can't give you an exhaustive analysis, and I'm not clueless about programming, so I can't tell you what it's like to learn programming from Python.

So, instead of giving an outstanding take on Python, I'll give you just a normal programmer's opinion. I'm not remarkable in the world of programming, so my opinion will probably be closer to yours than some coding luminary's. So here it is, Python through the eyes of a smalltime Javascript, ActionScript 3, PHP programmer. Please note, I just started writing Python a couple of days ago, so this evaluation will not be exhaustive.

However, even in that short time, I've noticed a couple things. First of all, I got a whole lot done. Even in the brief time that I've actually been writing scripts with Python, I've managed to replace a sizable amount of PHP code. I've almost finished writing an object-oriented Python include scheme for my websites.

I was going to put a paragraph here about how Python doesn't support private methods and variables, but then I googled "Python private methods" and found out how to make your methods private. You just need to add two underscores before the name of the method. I'm glad that I don't have to leave my programs' private parts exposed, but I'm disappointed that I had to backspace my eloquent and somewhat insinuating "No private methods" rant.

This topic will probably come back up later, when I have more of an opinion on Python. For now, I'm feeling a little too ignorant to continue.