Monday, 7 February 2011

Biomorphs and Javascript - a marriage made in purgatory.

Well it definitely isn't heaven, and it's not really hell (6502 assembly programming on a machine with no permanent memory and a dodgy power supply comes close).

I'm not sure I'm ready to devote a whole post to how crap Javascript is, I imagine that there are probably whole sites, probably complete universes, devoted to just that topic. But here's a handy hint -your variable isn't locally initialised unless you stick var in front of it, but your program will run anyway, perhaps almost correctly. Having been corrupted by languages where you don't declare variables, just use them, I got some unexpected side effects with the Biomorphs and the variables became global -even though they had been declared locally, inside a function scope. Enough, I've got to go and fill in the hole in the plaster where I was banging my head on the wall.

The biomorph program has had an overhaul and now produces, occasionally, things that look like biomorphs.  The main changes have been to switch from polar to Cartesian coordinates and to introduce randomness. The coordinate switch allows the introduction of a 'gene' as a string of x and y coordinates, and having this gene means that it can be populated randomly and thus gives us the potential for 'evolution'. Here's the guts :

function bio_morph()
        this.gene = new Array(9);

        //Generate a random gene 7 is the number of generations and gene 8 is the stem length
        for(var i = 0; i<7; i++) {
                this.gene[i] = Math.round((Math.random() * 20) -10);
        this.gene[7] = Math.random() * 10;
        this.gene[8] = Math.round(Math.random() * 10);
Multiplying by 20 and taking away 10 allows us to have negative numbers in our random sequence, so the creatures can gro up and down, left and right.

All that remains is to produce an array of the critters and allow you to choose the one start new generations from.

As always take a look at the main biomorph page.

No comments:

Post a Comment