The interlude is an introduction to the more advanced topic of a finite state machine, which should be in the tool-box of every software developer. It amounts to the simple idea of putting information in tables such that each row of the table can refer to another row in the table.
The example from the book is a map of rooms, which can be described by a table, where each row is a door (or hallway passage) from one room to another. In the code below, the table is represented by a dictionary.
Head,Tail = 1,0 |
D = {("NW",Head):"N",("N",Head):"NE", |
("NE",Head):"E",("E",Head):"SE", |
("SE",Head):"S",("S",Head):"SW", |
("SW",Head):"W",("W",Head):"NW", |
("NW",Tail):"W",("W",Tail):"SW", |
("SW",Tail):"S",("S",Tail):"SE", |
("SE",Tail):"E",("E",Tail):"NE", |
("NE",Tail):"N",("N",Tail):"NW"} |
room = "SE" # initial location |
print "Starting in room", room |
while True: |
cointoss = random.choice([Head,Tail]) |
room = D[(room,cointoss)] |
print "moving to", room |
choice
rather than "select". room
is the state
of the game in this simplified example; for a
real game, state might also include such things as points
earned, health, and other attributes. If the
game is a multiplayer game, then the state would
have such information for all the players (perhaps
the state would be represented by a dictionary).