Dirty dirty tracking in Pygame

January 26, 2010 at 00:53 (Coding) (, , , )

My latest little pet project, a game, has progressed far enough to have some rendering put in. I’ve always used Pygame for my games in Python. This started out as no exception.

Pygame uses SDL, in which rendering is simple but slow. You can get some quite significant speed boosts if you only redraw the pixels on the screen that actually change. So you keep track of where the sprite was and if it moved, you redraw the background there and then draw the sprite at the new location. DR0ID has a great article (scroll down to “Dirty Rects”) explaining this!

Anyway, I made a snippet to show how its done, the code is at the bottom of the post. Notice the use of Pygame’s sprite group LayeredDirty, it handles dirty sprites and keeps track of sprites moving across each other. In that snippet the Below class would be a background tile, Above would be the player’s avatar moving across it.

Screenshot

So theres two things I don’t like here. First, when implementing the rendering in my game, all of the drawing bugs were related to me forgetting to set the dirty attribute when I should have. Rendering code is boring to write, so I want it to be as simple as possible. In a perfect world, the sprite would keep track of its dirty status itself. This is also the reason for the title of this post, since its a cumbersome part of Pygame, its dirty. Get it?

Jokes aside, the second thing is that I go through all this trouble to gain some speed. But how much extra speed? How many sprites do I need to put into it before it starts to slow down? I plan to do some benchmarking on this (anyone know about any Pygame benchmarks by the way?).

The norm in systems like OpenGL or DirectX, more commonly used in games, is to redraw the entire screen each frame. That way you don’t have to care about dirty attributes. Those systems are also, at least as far as I know, faster than SDL. There are OpenGL libs for Python. I recently found the project Pyglet, which seems to be written as an alternative to Pygame. I’ll look into that, if it both easier to code in (no manual dirty tracking) and faster, there’s no reason not to switch.

Now for the code:

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((100,100))
background = pygame.surface.Surface(screen.get_size()).convert()
background.fill((0,0,255))

group = pygame.sprite.LayeredDirty()

class Below(pygame.sprite.DirtySprite):
    def __init__(self):
        pygame.sprite.DirtySprite.__init__(self, group)
        self.dirty = 1
        self.layer = 10
        self.image = pygame.surface.Surface((25,25)).convert()
        self.image.fill((255,0,0))
        self.rect = self.image.get_rect()
        self.rect.center = (50,50)

    def update(self):
        pass

class Above(pygame.sprite.DirtySprite):
    def __init__(self):
        pygame.sprite.DirtySprite.__init__(self, group)
        self.dirty = 1
        self.layer = 20
        self.image = pygame.surface.Surface((10,10)).convert()
        self.image.fill((0,255,0))
        self.rect = self.image.get_rect()
        self.rect.center = (25,50)
        self.going_right = True

    def update(self):
        if self.going_right:
            self.rect.centerx += 1
            if self.rect.centerx > 75:
                self.going_right = False
        else:
            self.rect.centerx -= 1
            if self.rect.centerx < 25:
                self.going_right = True
        self.dirty = 1

def main():
    Below()
    Above()
    while 1:
        for e in pygame.event.get():
            if e.type in (KEYDOWN, QUIT): return
        group.clear(screen, background)
        group.update()
        group.draw(screen)
        pygame.display.flip()

if __name__=="__main__":
    main()

Permalink Leave a Comment

Staying on topic

December 2, 2009 at 15:01 (Blogging) (, , , , )

One thing I didn’t decide on when starting this blog was the topic. I wanted to be able to write about anything that interested me. Nevertheless, a “topic” more or less evolved naturally. Although I haven’t really been able to figure out what it is, sometimes I don’t post something because I feel that it doesn’t belong on my blog, almost like its offtopic.

Disregarding the fact that its impossible to go offtopic on a blog without a topic, there are a few shortcomings I feel I have in my blog:

  • No schedule, since I haven’t found the discipline to take Jeff Atwood’s advice to heart.
  • No specific topic, for reasons stated above. Although I do not really care for readers, should I ever do, this needs to be improved.
  • No specific goal. Deciding on a topic and a long term goal may greatly increase the overall quality of the blog. As I will explain later, a “create games” category could contain simple tips about making games, with focus on actually completing the projects.

Is there a way to remedy this? During the past few days I’ve been sick and home from work, so I’ve had way to much free time to think about different ways to approach this. Looking through my blog archives, there seem to be a few topics I like to write about:

  • Programming, in general.
  • Creating games.
  • Open source applications and games, trying out new technologies I find.
  • Artificial intelligence/life.

Getting a discussion going is great, and that may happen if I manage to get some readers. In order to get readers that keep coming back, what I write about must interest them. Simple really. I’m so aware of this myself when reading my RSS feeds, some blogs have posts thats feels either irrelevant or very interesting.

I’ve toyed with the idea of creating separate blogs for each topic. I just started the Game Gardener to direct some of my “create games” posts that way. Although WordPress does a good job of letting one user create multiple blogs, I cant escape the feeling that now is the time to investigate if there is another way to handle this.

Is it possible to contain several blogs inside one blog? Whatever that means. Some clever use of a tag/category system coupled with a different theme for each category might get very far. Then, of course, the most important part really is to be able to offer a separate RSS feed for each “blog” (that is, each category).

I just read about Wolfire switching blog system, and through that found about bloggart code. An opensource system that might get some attention through Wolfire. Maybe I can take a look at the code, it could be possible to add my new-kind-of-category, that is a blog in the blog, in that.

Sections. I will call my new kind of super category a section. Yes.

Permalink Leave a Comment

Python 2d line-line intersection

December 1, 2009 at 19:18 (Math) (, , , , , )

I needed a quick 2d line-line intersection algorithm in Python. A few googles later I had combined

  • The vector 2d class found in the python cookbook.
  • A nice CCW test to speed it up a little with the early filtering.
  • And the main formula for finding the actual intersection coordinate.

The code, including a graphical demo, can be found over at refactor my code.

Permalink Leave a Comment

Markdown

November 27, 2009 at 01:01 (Blogging) (, , , , )

When I write my blog posts I usually write the html by hand in the HTML view of WordPress. Quite cumbersome when you get long paragraphs, especially when they also contain a few links.

Before I knew it I was hacking away at a Python script that converted text between set characters into HTML. For example, I turned _link_url_linktext_ into <a href="url">linktext</a>.

As I was doing this the syntax evolved and became more and more like the system used for input over at Stackoverflow. My subconscious was reminding me how the syntax worked and I reimplemented it. When I became aware of this, I stopped, went to Stackoverflow and checked the formatting help section. Quite funny actually.

The system used is called Markdown, and is designed specifically so you can write webcontent without making the actual source text a complete and utter mess.

I did some searching for a good “editor” and found one called Showdown. Im actually on that site as Im tying this. There are two things I like about it:

  • What I type is converted in realtime, so its near impossible for syntax errors to go unnoticed.
  • I can switch from the preview mode (rendered html) to raw HTML output, which is needed since I need to paste the entire thing into WordPress when Im done.

I threw away my hacky script, since Im currently not planning to learn more about wheels, I just want my postwriting to be a bit easier.

Interested? Just head over to Showdown and start experimenting, if you get stuck, check the full Markdown syntax reference.

Permalink Leave a Comment

First impression: Chrome OS

November 24, 2009 at 22:02 (Uncategorized) (, , , , , )

Finally found the time to give Googles new operating system a spin.
Chrome OS Logo

Its really easy to do it. Found a great blog post through Lifehacker.

  1. Download torrent file.
  2. Read the chromium_os_usb.txt for how to burn the chrome_os.img file to a usb drive (needs to be at least 4GB)
  3. Be grateful for Win32DiskImager, great app!
  4. Reboot the box, remember you might have to change your BIOS settings to boot from the usb drive

If youre lucky, you should see the splash screen right about now. Remember the login details (also in the readme file):

  • Username: chronos
  • Password: password

Chrome OS Login Image courtesy of Lifehacker

For me it started up in just over 10 seconds (give or take), I wonder how fast it would have been if I didnt boot from a usb drive. Login in was easy and the very instant I pressed enter the browser presented itself to me. Very zippy.

Now to first part that was a bit problematic. I wasnt connected. You have to click the middle button (of three) in the upper right corner and select which network you want to connect to. I assume that this happens automatically if you run a wired network.

I surfed around, checked the apps. I was suprised how fast my little Eee PC could run when all it needed to care for was a browser. Also checked a video on youtube to make sure sound worked, and it did.

I tried it on my second laptop as well, not much luck there. It booted alright but, apparently, it couldnt find the correct wireless network drivers. Needless to say, it made Chrome OS quite useless.

So the first impressions? Meh. I mean it was ultra-speedy (very nice) but I couldnt find how to change the keyboard layout, and I dont like qwerty. Besides, I mainly write code on my netbook and if my OS wont let me get some compilers, its quite useless.

It is a fancy and turbocharged Chrome Browser, you have seen it before. Still, I want to recommend it to any geek having a few hours to kill.

Permalink Leave a Comment

Clonk is open source!

October 21, 2009 at 22:06 (Coding, Making Games) (, , , , , , , , , )


Screenshot of the original Clonk Rage, clickthrough leads to more screenshots.

A quote from the webpage:

OpenClonk will be the Open source successor of the Clonk gaming series.

In early march 2009, Matthes Bender told the other developers of Clonk Rage that he wouldn’t have any time to work on Clonk anymore. As the Game Designer of Clonk Rage and Directing Manager of RedWolf Design, the company selling the Clonk titles, he left a significant vacancy. The development of Clonk Rage was mostly done as a hobby by the other developers, and although they wanted to continue doing that, they felt that more contributors were needed. Thus it was decided to radically lower the barriers for new contributors by publishing the source code to the engine, allowing everyone to freely modify the source code and game content, and discuss the future directions in an open forum. It was also decided to drop a lot of the “old” game content and drop the backwards compatibility requirement. The goal is to encourage new people to participate, while allowing the Clonk Rage developers to continue working on at least some of the code they produced and are familiar with. There are also plans to continue the clonk.de league for registered players for those who want to play in a supervised league.

Didnt take me long to hunt down the download link in search for the latest source.

~/code/openclonk$ hg clone http://hg.openclonk.org/ openclonk

There was a README.linux.txt in there. I read it and made sure I had all the dependencies installed (I actually missed a few).

Then I could finally run:

~/code/openclonk$ autoreconf -i && ./configure && make

After watching the compiler work for a while I got a:

make: *** [all] Error 2

Bah!
Went to the FAQ … nope, not much development related stuff there. The forums? Hmm… found irc, logging on… stating problem…

Tried ran make again, to get a shorter error message, make gave me this:

~/code/openclonk$ make
make all-am
make[1]: Entering directory `/home/mizipzor/code/openclonk'
make[1]: *** No rule to make target `src/platform/DInputX.cpp', needed by `DInputX.o'. Stop.
make[1]: Leaving directory `/home/mizipzor/code/openclonk'
make: *** [all] Error 2

After some chatting the time came for a:

~/code/openclonk$ hg pull && hg update

Then I charged ahead on with another

~/code/openclonk$ autoreconf -i && ./configure && make

The latest changeset seems to have done the trick, compile successful… now lets find a binary executable!

~/code/openclonk$ ./clonk
[21:09:22] Using XRandR version 1.3
Warning: ForEachFile with * (/home/mizipzor/code/openclonk/./*.c4p)
[21:09:22] No valid key file found.
[21:09:22] Error opening system group file (System.c4g)!

Bah! (again)
Apparently, clonk needs to be executed from within the planet subfolder. One symlink coming up:

~/code/openclonk$ ln -s ../clonk planet/clonk
~/code/openclonk$ planet/clonk

Yay! Game started… in an unsupported monitor mode… which totally foobar’d my desktop… but it starts! :D

If you followed this… “guide”, if i may, as a linux developer I then urge you to to add NewGfxCfgGL=1024 under the [Graphics] section in ~/.clonk/openclonk/config to start the game in windowed mode.

Happy hacking! The bug tracker is this way.

Permalink Leave a Comment

GPU problem (NVIDIA GeForce 9600M)

October 21, 2009 at 20:13 (Hardware) (, , , , )

Just a few days since my laptop returned from repair it started to behave weird again. Graphical artifacts corrupted the screen beyond readability. Its been almost a year since I last did a clean wipe on it so I thought maybe now is the time. Grabbing a random rescue CD from the pile I quickly formatted the entire harddrive. After that, the Windows XP CD was inserted and I thought the computer wasnt far from being reborn. I was very wrong.

With a clean system, no artifacts were seen. But as soon as the GPU drivers were installed, the artifacts returned. Removing the drivers got rid of the artifacts. Below is a screenshot of a fresh install of Windows XP, no service pack, patches or updates, it doesnt even have an internet connection. Just the GPU drivers have been installed:

I kept juggling this for a while. Un-installing drivers in safe mode, installing them again, running various driver cleaning software and installing other versions of the driver. Nothing seemed to work. And note that (one version of) the failing drivers were the very ones supplied on the driver CD that I got with the laptop which I ran with, completely without problems, during the first few months.

Something was seriously broken here. A bit frustrated, I started googling. And troubling search results werent few and far between.

Okay, so that glitch seems to have occurred since quite a while ago. But now for the real heavy weight! If you are to click any links or read anything through this post, let it be this one. Its a great, and long, post (on TheInquirer) detailing what seems to be a major cover up operation in the works by Nvidia to hide all the defective GPUs.

All the computers Ive bought over the years have used the Nvidia cards. But this problem and the resulting search results on Google have made me hesitate to go with them again. The main reason for buying the GeForce cards have been for the, actually quite good, Linux support. Time to check again now how ATI is doing on that front.

Im still waiting for my laptop to return from the service job. If it works when it gets back (that is, they dont simply blame Nvidia and send it back as is), and how well it works will be the real judge in this scenario.

Permalink Leave a Comment

Trying out Tumblr

September 22, 2009 at 15:23 (Web) (, , , , , , , )

Just found Tumblr and have tried it out and read some about it during the last few hours. What I like about it is that there seem to be a culture and orientation in it thats weighted towards the reposting/reblogging/retweeting thinking thats currently popular on the internet.

Tumblr Logo

This post is a mere “train of thought” thats supposed to include what I would use Tumblr for and how I will benefit from it. Currently Im a member of many different sites and forums on the internet, keeping track of what Im doing and what I like all over the place is hard. Tumblr would be nice in the way that I can sort of scoop up everything Ive seen (and “Liked”) into one place. This is what I intended Delicous to be for me, but its heavy link orientation and lack of personal comments made it… a bit boring, frankly.

But thats good, thats the way it should be. I, myself, is a firm believer of the “right tool for the right job” philosophy. You should post links to Delicious, videos on Youtube. There are countless hosts and systems for images and blogs thats good enough. The thing is, every content should go to a site specifically designed to handle that content. What I currently lack is the metasite where I can find links to all my content spread all over these specialized sites.

From the top of my head, this is what I would like to end up on Tumblr:

  • My favorites on youtube
  • My questions on Stackoverflow
  • Posts on this blog
  • Everything I “Starred” in my Google reader account
  • My links saved on Delicious

I think I read somewhere on the Tumblr site that it can import and post everything listed in a RSS feed. That would be the absolute killer feature for me. Most of the stuff listed above can already be retrieved via RSS. And what cannot yet be retrieved is a small enough and fun project to do myself.

No site would never (and should never) survive if its supposed to handle every content in a good way. This is one of the reasons why I dont like Facebook. “The right tool for the right job”. Tumblr could be the right “tool” for the “job” of collecting everything interesting I find (and create) on the internet, with no focus in itself on original content.

Permalink Leave a Comment

Simulating a tree

July 26, 2009 at 03:28 (Behavioral Modeling) (, , , , , )

Since I’m making some progress with the game Genetic Tree Garden, It was inevitable that I began thinking about advancing to the next step. In the GTG project, I defined a DNA (number sequence) from which a tree could be drawn. The trees could also be merged/bred.

But there was no logic. What would be required for a tree to come alive?

I sat down with a few blank sheets of paper and began thinking. Whenever you aim to simulate something, its more important to decide what parts from the real world you will simplify to the extreme, or remove altogether, rather than how you implement the parts you want to keep.


Image source

There are a few parts/features of the tree I took special interest in:

1. The crown

The most interesting part of the crown are the leaves. Using carbon dioxide, water and the energy from the sunlight, the leaves produces organic compounds, especially sugar, through the process of photosynthesis.

By making a tree tall and wide, we get more sunlight than the surrounding trees, which would make for an interesting part if this would be put into a simulation using genetic algorithms and natural selection.

2. The trunk

Thick, wide and robust, serving as protection for the tree. It also (obviously) keep the crown elevated. A massive trunk makes the tree very resistant to wind and the gravity trying to pull the crown to the ground.

But the most interesting aspect of the trunk is its purpose of transporting chemical compounds between the leaves and the roots. It’s interesting because we need to define and implement a circulatory system, and depending on the number of compounds we want to include in the simulation, this system could very well turn out to be extremely complex.

3. The roots

I’ve got mixed feelings about the roots. They are involved in countless extremely interesting processes, including symbiosis with bacteria and storage for nutrition. They also produce cytokinin, which controls tree growth, and the visual growth of the tree would probably a very important (or at least rewarding) part of the simulation, making that process important to understand.

On the other hand, once we start looking into those concepts, the complexity of the simulation starts to increase extremely rapidly, making it a logical decision to skip the most advanced (but also most interesting) parts.

The roots also anchor the tree to the ground, making it resistant to hard wind.

Simplifying

I’ll probably turn the leaf into a simple machine that releases one unit of sugar for every one sun- and water unit it receives and give the roots the sole purpose of introducing water into the tree. The branches themselves uses the sugar to grow.

This way, we made the simulation all about the circulatory system. Maybe some self organizing cellular automata rule can be applied to it. Or maybe even a more complex dynamic fluid system. Either way, it will indeed be quite an interesting project to look more into later.

Permalink Leave a Comment

Genetic Tree Garden

July 21, 2009 at 20:50 (Making Games) (, , , , , , , )

My latest experiment with genetic algorithms now got enough in it to warrant a tag as 0.1 and a post in my blog. The concept of this soon-to-be game is the genetic algorithm and the way two sets are merged.

Building upon the fractal tree I made, which is entirely defined by numbers, we can merge two trees together by simply calculating the average of all their values. Then, by adding some mutation, we have something that resembles the natural evolution. I plan to cover the math behind this in greater detail in another post.

Use the mouse to select two trees and press space to merge them. That’s pretty much all there is to it, but note that this is just version 0.1.

How to install:

  1. Download and install (if you haven’t) python 2.5.4
  2. Download and install (if you haven’t) pygame 1.8.1
  3. Download the game and extract it to a folder of your choice
  4. Navigate into the folder and doubleclick game.py to play!

I plan to add some sliders that controls the merges and mutations, as the game intends to demonstrate how it works. Some sounds for user input feedback. And, maybe most importantly, an objective or score measure to turn it into an actual game. The objective would probably be something along the lines of growing a specific looking tree, turning this into… like… a virtual tree breeder/gardener game.

Permalink 1 Comment

Next page »