Saturday, 12 February 2011

The Tao of Programming

The Tao of Programming by Geoffrey James
The Tao of Programming by Geoffrey James is a short book of humourous computer parables inspired by an ancient Chinese text, the Tao Te Ching.

The Tao Te Ching is believed to have been written 2500 years ago by Lao Tzu and provides the basis for Taoist philosophy. The book is separated into 81 (34) short chapters of parables and proverbs.

James divides The Tao of Programming into 32 (25) chapters, a mix of tales paraphrased from the Tao Te Ching and anecdotes advocating the key principles of the hacker ethic:

  • code should be small, elegant and easy to read
  • management shouldn't interfere with programming

The preface (not included in the online copy) describes how James, an amateur computer archaeologist, stumbled upon and decoded The Tao of Programming while searching through a stack of obsolete punch cards.

My favourite chapter has to be the description of well-written programs closely followed by Turing's dream:

“A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity.”
-- The Tao of Programming, Chapter 4.1


“Grand Master Turing once dreamed that he was a machine. When he awoke he exclaimed:

‘I don't know whether I am Turing dreaming that I am a machine, or a machine dreaming that I am Turing!’”
-- The Tao of Programming, Chapter 2.2



Although the book is short and you probably won't learn anything new, it's definitely worth a read if you have 30 minutes to spare.

Wednesday, 2 February 2011

Celebrating 30 Years of Color Robot Battle

Color Robot Battle
Color Robot Battle is one of the earliest commercial programming games, published 30 years ago for the TRS-80 Color Computer by The Image Producers.

The game is played by writing programs to control a robot's movement, sensors and weapons. Programs are written in a hybrid of the BASIC / Logo programming languages. Two robots enter an arena with the survivor being declared the winner.

I asked the designer and programmer of Color Robot Battle what inspired the game:

“Well, the Apple II program did along with the feeling I could do it better. All of these were initially inspired by Core Wars, I believe. I did want to make the language complete enough to have quite a bit of control and flexibility over the robots.”
-- Glenn Sogge

“The robot controlling programming language was based on BASIC. Prior to working on CRB, I'd written a simple BASIC interpreter for the PDP-11, so it was a natural choice.”
-- Del Ogren


Color Robot Battle is a fantastic example of compact code. The game, compiler and full screen editor are all written in 6809 assembly language and somehow manage to fit on a 4K ROM.

Although the language of CRB only takes a few minutes to learn, a whole range of strategies are possible. There are four types of command available:

  • movement: followed by a number. Movement commands are F(orwards), B(ackwards), L(eft), R(ight), H(alt), T(urn), D(irection).
  • conditional: detect what the robot is facing. =(true) or #(false) followed by R(obot), W(all), M(issile), L(aser), S(omething - any direction), ?(random).
  • flow control: C(all) or G(oto) a label. Labels are defined at the beginning of a line and terminated by a >.
  • attack: XL to fire the laser or XM to fire a missile.

The program starts at the label START>. Multiple commands on one line are separated by a colon :. If a condition fails the rest of the line is skipped.

Here's a simple example that manages to win a few battles:

*SIGMA               ; robot name
START>               ; start here
F5                   ; move forward 5
=W:T1                ; if facing a wall, turn 45°                
=?:T1                ; randomly turn 45°
=R:XL                ; if facing a robot, fire laser
GSTART               ; repeat from start

Thanks to the simplicity of the language, CRB makes the perfect introduction to programming games. So, does anyone fancy a tournament? ;-)


Color Robot Battle's editor

Sunday, 30 January 2011

Interactive Fiction: 4K Adventure

Text Adventure: 4K Adventure

I've always been a fan of text adventures - exploring a fantasy world, drawing a map and solving a few puzzles along the way. A couple of my early favourites were The Hobbit and Heroes of Khan. When I discovered shareware I spent hours puzzling over Humbug, Curses and t-zero. Even now I'm still working through The Lost Treasures of Infocom :-)

So when I needed a project to exercise my new 8086 assembly skills a text adventure seemed the natural choice. I decided to cram as much as possible into a 4K program - verb-noun parser, text decompression and a snowy forest to explore.

After 35 hours coding I'd created 4K Adventure complete with dwarves, mischievous elves and stolen magic. It managed to work despite the spaghetti code and a couple of dubious algorithms!

Impressed that I'd actually completed a project I immediately started work on a sequel and a simple operating system...  I still haven't completed either. Maybe one day ;-)

Thursday, 27 January 2011

CoreLife: Artificial Life Simulator

CoreLife core monitor

A few years ago when using either Lycos or the WWWW (remember those?) to search for CoreLife I came across a program with the same name. The program I discovered is an artificial life simulator written by Erik de Neve.

CoreLife supports two VCPUs:

  • The CoreLife VCPU - supports 32 instructions that resemble 8086 assembly
  • The Tierra VCPU - supports the 32 instructions of Thomas Ray's software

After seeding memory with a handwritten organism the simulation begins. Each organism attempts to replicate while the simulator randomly mutates instructions or causes them to fail. Thanks to the mutation the copied organism often differs slightly from the parent.

In some cases the mutation renders the child organism less effective or too damaged to replicate. In other cases the child is smaller and faster, able to out-replicate the less efficient parent.

Watching the code evolve made me wonder if I could beat evolution. I set myself a challenge: could I create the ultimate organism to out-replicate everything else and resist mutation?

Unfortunately any attempt to resist mutation quickly died out so I settled for creating the smallest self-contained replicator, just 22 instructions:

;22 Instruction Replicator
;for the Tierra Virtual CPU
nop_1
adrb
nop_0
push ax
sub_ac
divide
mov_ab
adrf
nop_1
sub_ab
inc cx
mal
nop_1
dec cx
mov_ii
ifz
ret
inc bx
inc ax
jmpb
nop_0
pop dx

CoreLife statistics

Wednesday, 12 January 2011

Recursion via Pascal

Recursion via Pascal by J.S. Rohl
Recursion via Pascal by J. S. Rohl is one of a small number of books devoted entirely to recursion in programming. Recursion is a technique where a problem is defined in terms of a simpler version of itself.

The book has over 100 examples and although the code is in Pascal it shouldn't pose too much of a problem for C / Java programmers.

Factorials are the classic example of recursion:

The factorial of a number n (written as n!) is the product of all positive integers below or equal to n.

6! = 6 × 5 × 4 × 3 × 2 × 1 = 720.

n! can be defined recursively as:

0! = 1
n! = n × (n-1)!

Here's the code to calculate factorials in Pascal:

function factorial( n:integer ):integer;
begin
    if n = 0 then
        factorial := 1
    else
        factorial := n * factorial( n-1 )
end

Or in C:

unsigned int factorial( unsigned int n )
{
    if ( n == 0 )
        return 1;
    else
        return n * factorial( n-1 );
}

Or Forth:

: factorial
    dup 0= if
        drop 1
    else
        dup 1- recurse *
    then
;

Rohl first examines some simple examples of recusion: factorials, highest common factor and displaying numbers before moving on to more advanced topics:

  • two-level procedures
  • recursive data structures
  • binary recursion
  • recursive sorting algorithms
  • mutual recusion

Throughout the book Rohl compares the runtime / complexity to the equivalent iterative code and warns against any potential pitfalls. My favourite example is the code to calculate x^n from “developing the power example, a cautionary tale”:

function p(x:real; n:integer):real;
begin
  if n = 0 then
    p := 1
  else if odd(n) then
    p := p( x, n div 2 ) * p( x, n div 2 ) * x
  else
    p := p( x, n div 2 ) * p( x, n div 2 )
end

Thanks to a small oversight the order of complexity is Ο(n) instead of Ο(log n).

Recursion via Pascal was published in 1984 but remains relevant despite it's age. The text is easy to follow and I'd recommend the book to anyone curious enough to delve further into recursion :-)

Thursday, 23 December 2010

#CarolsInCode - Top Five Countdown

#carolsincode
#CarolsInCode is a programming meme with a seasonal twist. Short programs are used to encode the lyrics of a Christmas carol. Some display the lyrics when the program runs while the more ingenious examples define the song with the program's control structures.

For example in JavaScript:

while ( shepherds.watch() == 'flocks' &&
  date.getHours() in night )
{
  lord.angel--;
  glory.shone_around();
}

This is While Shepherds Watched Their Flocks by Nahum Tate:

“While Shepherds watch their flocks by night,
All seated on the ground,
The angel of the Lord came down,
And glory shone around.”

Here's the top five countdown of the very best #CarolsInCode. Can you identify all five? Is your favourite missing?

GrumpyWookie:

Weather.Outside="frightful";
Fire.Delightful=true;
Lights.Luminosity=WayDownLow;
for (int i=1; i<=3; i++) { LetItSnow(); }

ShinyEmptyHead:

public Sleigh sleigh;
public void dashThroughSnow()
{
int horses = 1;
sleigh = new Sleigh(horses);
for (Field field : fields)
{
laugh();
}
}

JohnGirvin:

var wenceslas = new Person({
    rank: 'king',
    alignment: 'good'
});
$.bind(FeastOfStephen, function() {
    wenceslas.lookOut();
});

Costall:

if (DateTime.Now()=="25/12/2010")
{
for (i=0;i<3;i++) Ship[i].Visibility = Visibility.Visible;
}

GrumpyWookie:

Kiss.PersonA="Mummy";
Kiss.PersonB="Santa";
Kiss.Witness=Me;
Kiss.Location=Mistletoe.Underneath;
Kiss.Time=Date.LastNight;

More #CarolsInCode




#songsincode, lyrics for programmers

Friday, 17 December 2010

#carolsincode - Christmas for Programmers

#carolsincode
#carolsincode are small pseudo-programs which contain a Christmas song. Some examples display the lyrics while others use the program's control structures to define the song.

Here are five examples in C, CSS and JavaScript. Can you do better? ;-)

var kings=new Array(3);
for (x in kings)
{
  kings[x].origin='orient';
  kings[x].bearingGift=true;
  kings[x].travelled='afar';
}

main() {
  int a;
  for (a=1;a<5;a++) printf("Noel, ");
  printf("Born is the King of Israel.");
}

#rudolf .nose {
  color: red;
  background: url('very_shiny.jpg');
}

while ( shepherds.watch() == 'flocks' &&
  date.getHours() in night )
{
  lord.angel--;
  glory.shone_around();
}

for ( c=1, c<=4, c++)
{
  noel()
};
king = new Object();
king.kingdom = 'Israel';