Posts Tagged ‘Python’

Talking Python

April 25, 2010 1 comment

The following was a small amusement that I put together for my 5 year old daughter. It must have made quite the impression on her as she has informed me that she wants to be a “horse programmer” when she grows up.

This program relies on another program called “espeak” which should be present on most Linux systems. This is a command line tool which takes  text and converts it to speech. If you are using a Mac you could adapt the program to use the command “say” which does the same thing (the command line arguments are bound to be different though). Windows doesn’t include such a tool, because Microsoft just doesn’t love you, however Google turned up this result when I searched for “Windows command line speech”.

Apart from that you will see a few Python constructs which may be interesting to Python newbies, such as calling another program from within your Python script, and generating random silly sentences.

Note that it also uses the new style of string formatting so you will need at least Python version 2.6.

#! /usr/bin/python

import subprocess
import random

def say(sentence):
    speed = "-s " + str(random.randrange(120, 200))
    pitch = "-p " + str(random.randrange(100))["espeak", speed, pitch, sentence])

sentences = [
    "Hello {name}.",
    "{name}? What a {adjective} name!",
    "Congratulations, {name}! You have won a {noun}!",
    "Excuse me {name}. Have you seen my {adjective} {noun}?",
    "Hello {name}. Are you going to Wellington Zoo soon {name}?",
    "What is your name {name}? Oh, that's right, silly me. Your name is {name}!",
    "{name}! Your {adjective} {noun} is {verb}ing! {adverb} grab a {noun2}, {name}!",
    "What is your favourite {noun}, {name}? Is it the {adjective} one?",
    "Quickly quickly {name}! No and Yes!",
    "Where's your mummy {name}? Is she {verb}ing today?",
    "That's what I said {name}",
    "What are you doing {name}? Are you {adverb} {verb}ing? Do you think that's a good idea?",
    "{noun}s are fun. Don't you think so {name}?",
    "Red alert. We go beserk. No {name} moves, no {name} gets hurt.",
    "Please {name}. May we go to the {noun} shop?",
    "Happy birthday to you. Happy Birthday to you."
    " Happy birthday dear {name}. Happy birthday to you!",
    "This is a shout out to {name}. Keep it real homey.",
    "Last night I had the strangest dream. {name} was {adverb} riding on "
    "a {adjective} {noun}, being chased by a thousand {adjective2} {noun2}s. "
    "Luckily, the {noun} was just too {adjective} for the {noun2}",
    "{name} is a good reader!",
    "Time for bed {name}. Go on... off you go!",
    "Make me a {noun} {name}, as fast as you can! I would like a {adjective} one please!",
    "Who ate all of my cake? {name}, was it you?",
    "I'm lost {name}! Can you tell me where I am?",
    "Do you like the circus {name}?",
    "This is the {adjective}est {noun} that I have ever seen. It is even more {adjective} than "
    "that {noun2} that I saw yesterday. Although, to be honest, that {noun2} "
    "was probably more {adjective2} than {adjective}",
    "I just saw a {adjective} {noun} {adverb} {verb}ing a {adjective2} {noun2}.",
    "Never let a {noun} {verb} more than once a day, otherwise it may {adverb} turn "
    "into a {noun2}",


nouns = [
    "Chestnut Park",
    "soccer ball",
    "X box",

adjectives = [

verbs = [

adverbs = [

n = ""
while True:
    n = raw_input("What is your name? ")
    if not n: break
    #[say(word) for word in random.choice(sentences).format(name=n).split()]
    for i in range(3):
                                            noun = random.choice(nouns),
                                            noun2 = random.choice(nouns),
                                            verb = random.choice(verbs),
                                            adverb = random.choice(adverbs),
                                            adjective = random.choice(adjectives),
                                            adjective2 = random.choice(adjectives),


Making a rogue-like game with libtcod

February 2, 2010 2 comments

Well I haven’t yet made a roguelike game, but I have completed a short tutorial on using the libtcod library.

Trapped in a lonely dungeon. Wait... who's that?!

Libtcod is a library with wrappers available for numerous programming languages which aids in the creation of roguelike games. I happen to be using the Python wrapper.

It provides a special true-colour console with plenty of neat tricks like customizable fonts, blitting of images and off screen drawing areas. These provide the potential for some stunning visuals that still have a blocky, old-school, feel.

While I’m sure these facts alone would make it useful for a great many styles of game, libtcod also provides numerous helpful toolkits which, for the most part, are aimed at roguelike developers.

Basically all of the standard routines that you would otherwise need to figure out for yourself before you can start designing your unique game. These include:

  • Field of view toolkit. What can you see in the dungeon… where does your torchlight fall?
  • Path finding toolkit. Compute the path from A to Z in your dungeon.
  • Keyboard and mouse support
  • BSP dungeon generation toolkit. Tweak the parameters for dungeons, towns, forests or whatever.

Plus a few more neat features you may not have ever imagined you would need for a roguelike:

  • BMP and PNG support
  • Heightmap toolkit 😯
  • Perlin noise support. Hmmm… ocean anyone?
  • Random number and compression toolkits

It’s probably important to note that you can use any or all of the toolkits that you choose… If you would prefer to implement your own dungeon generator for example, that’s fine too. In fact there is still plenty of work still to be done as a game developer. For instance, libtcod won’t implement the monster AI or combat for you (yet).

Lately I’ve been focusing on learning C++, and if I’m to learn one new language a year (which seems a reasonable goal) then this is certainly the year of C++. However, I would also like to have fun with a language that I already know well (ie. Python), and this is where I see libtcod fitting in. My verdict so far is that I like this library and I think I could have a lot of fun tinkering with it.

I’ll post my game here when it’s awesome 😀

Crikey, I nearly forgot! The tutorial that I was blathering on about at the top of this post is here. At the time of writing this only the first part has been written, but that is enough to create the explorable dungeon level seen in the screenshot above. Here’s hoping that the authors finish the remainder of the tutorial sometime soon.


January 19, 2010 Leave a comment

So I’m hooked on SPOJ again. For this burst of enthusiasm I’m using C++, both to increase my skills and to clean up some of the problems that my Python solutions could not solve in the given time limit.

Of course this process does not produce many (any) pretty pictures, therefore not much content for this fledgling blog.

Still, maybe I’ll discover some sort of algorithm or something.

I was rather proud of myself for figuring out the relationship between the curved perimeter of a semi-circle and its area (yes, pretty advanced stuff, I know :-P). Where “p” is the curved part of the semi-circle’s perimeter, and “A” is the area:

A = \dfrac{p^2}{2\pi}

I don’t want to give away exactly which problem this was for, but it would sure be useful if you needed to enclose the maximal space possible against an infinitely long wall by adding a fence of a given length and arbitrary shape which touches the wall at exactly two points.. *cough* 😉

Categories: C++, Plans, Python Tags: , , ,

It’s Compilin’ Time!

January 10, 2010 Leave a comment

Further to my last post, I actually have coded a very simply Mandelbrot set renderer in C++.

I’m quite familiar with the basic syntax of C++, so at the outset I though the main challenges would be:

  1. dealing with complex numbers
  2. saving the results as an image file

After some mild Googling both of these challenges were surmountable.

C++ has a standard library header “complex,” which implements complex as a template class. Whatever that means. Anyway, import “complex” and you now have complex number support. See the code below for a demonstration.

For PNG support I used PNGwriter (also available in the Ubuntu repos). PNGwriter’s project site has plenty of example code, and the usage seems very straight forward. The only stumbling block (for me at least) was getting the compiling options right to “link” the PNGwriter library. As it turns out, some or all of the following command is required to compile this code:

g++ main.cpp -o my_program `freetype-config –cflags` -I/usr/local/include -L/usr/local/lib -lpng -lpngwriter -lfreetype

Aside from that bit of unpleasantness, it was really no harder to write this in C++ than in Python. Here it the finished code:

#include <iostream>
#include <complex>
#include <pngwriter.h>

using namespace std;

int main()
    int bailout = 256;
    int size = 800;
    pngwriter png1(size,size,0,"mandel2.png");

    for(int x=0;x<size;x++)
        for(int y=0;y<size;y++)
            int i = 0; //iterations
            complex<double> c(x/(size/4.)-2, y/(size/4.)-2);
            complex<double> z(0, 0);

            while(abs(z)<2 and i<bailout)
                // iterate through mandelbrot dynamic
                z = pow(z, 2) + c;

                // c is outside the mandelbrot set
                float value = (float) i / bailout;
                png1.plot(x, y, value, value, value);

        } // for y
    } //for x


    cout << "done!" << endl;

    return 0;

Remember, if you want to try running this code you will need the PNGwriter library.

The output is of course no different from the Python version that I posted previously, but here it is for the sake of completeness:

The Mandelbrot Set

The Mandelbrot Set

See Plus Plus

January 7, 2010 Leave a comment

These Buddhabrot scripts can sure be processor intensive. I would be better off programming them in C or C++, much as I do love Python. They are rather trivial, so it shouldn’t be too difficult.

One purpose of this blog is to openly record my musings of the various things that I think I ought to do—in the hope that I may remember to actually do them. This is but one such open musing.

Buddhabrot Chromatica

January 2, 2010 1 comment

In my previous post on Buddhabrots I demonstrated that different iteration or “bail-out” levels can produce different looking Buddhabrots. Buddhabrot discoverer Melinda Green also described the method of mapping differently-iterated Buddhabrots to the different channels of an RGB image. This can result in strikingly “Nebulous” images, reminiscent of those famous images from the Hubble space telescope.

Obviously this was the next thing I had to try.

3000r, 1500g, 500b. Channels normalized individually.

This image uses 3000 iterations on the red channel, 1500 on the green channel, and 500 on the blue channel. I have normalized the channels individually which seems to favor the channel with the least iterations.

3000r, 1500g, 500b. Channels normalized together.

This images uses the same configuration of iterations per channel as the last. This seems to favor the channel with the most iterations.

It strikes me that both of these approaches are rather arbitrary. The best solution would be to combine the channels in a decent image editing program and adjust the levels of each until the result is visually appealing (These images had their channels combined at creation time in Python). Unfortunately GIMP is not the decent image editing program I’m looking for. CinePaint, however, seems perfect for this job.

1000r, 200g, 100b. Adjusted in CinePaint

“To infinity… and beyond!”

1000 iterations red, 200 green, 100 blue. Adjusted to Hubbletastic perfection. Thanks CinePaint!

The next step is probably to render some super-big color images.