Re: Factor

Factor: the language, the theory, and the practice.

HAMURABI

Tuesday, August 3, 2010

#games

A few days ago, a programming challenge was made to port a game called HAMURABI from BASIC to a modern programming language.

Obviously, I thought Factor would be a fun contribution.

Warning: there are some spoilers below. If you plan on implementing this on your own from scratch, you might not want to read further.

The game consists of a simple concept. You are governor of “ANCIENT SUMERIA” and are responsible for certain yearly operations:

  • managing the purchase or sale of land,
  • feeding your people from stored food,
  • and planting seeds to grow food for the future.

Depending on how well you do, you might be lauded, hated, or even impeached over the course of your 10-year term in office.

One way of thinking about a problem is to start from the outermost process: welcome the user, create a game, run 10 years, and then finish with a summary. This can be expressed pretty directly:

: hamurabi ( -- )
    welcome <game> 10 [ year ] times finish ;

The main game logic is in the year word and consists of a series of steps:

: year ( game -- game )
    [ 1 + ] change-year
    report-status
    update-randomness
    trade-land
    feed-people
    plant-seeds
    update-stores
    update-births
    update-deaths
    check-plague
    check-starvation ;

The entire solution (about 250 lines of code) is available on my GitHub. Other solutions have been contributed including Java (150 lines), Lua (185 lines), and Common Lisp (190 lines).

You can run it from the command line:

$ ./factor -run=hamurabi

Or, you can run it from the listener:

IN: scratchpad "hamurabi" run
                                HAMURABI
               CREATIVE COMPUTING  MORRISTOWN, NEW JERSEY



TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA
SUCCESSFULLY FOR A TEN-YEAR TERM OF OFFICE

HAMURABI:  I BEG TO REPORT TO YOU,
IN YEAR 1, 0 PEOPLE STARVED, 5 CAME TO THE CITY
POPULATION IS NOW 100.
THE CITY NOW OWNS 1000 ACRES.
YOU HARVESTED 3 BUSHELS PER ACRE.
RATS ATE 200 BUSHELS.
YOU NOW HAVE 2800 BUSHELS IN STORE.
...