[Tutor] results not quite 100 percent yet

bob gailer bgailer at alum.rpi.edu
Wed Jan 30 20:24:35 CET 2008

bhaaluu wrote:
> #             N S E W U D T
> travelTable=[[0,2,0,0,0,0,0],    # ROOM 1
>              [1,3,3,0,0,0,0],    # ROOM 2
It is good to finally see that you are building an adventure game.

Consider creating a instance of a Room class for each room and saving 
them in a collection such as a list.

This will give you much more flexibility as your game grows.

Inevitably I wound up doing a bunch of things more "Pythonically" so 
there may be stuff here you don't relate to yet. But is is all worth 
studying and will save you hours of headache later.

----------------------------- code -----------------------------
import random
class Room:
  roomNo = 0
  def __init__(self, destinations, updatable=True):
    Room.roomNo += 1
    self.roomNo = Room.roomNo
    self.destinations = destinations
    # store treasure apaart from destinations
    self.treasure = 0 # add intial treasure
    self.updatable = updatable # may have the treasure updated
  def updateTreasure(self, treasure):
    self.treasure = treasure
  def __repr__(self):
    return " %s:%s" % (self.roomNo, self.treasure)

rooms = [
  Room([0,2,0,0,0,0]),  # ROOM 1
  Room([1,3,3,0,0,0]),  # ROOM 2
  Room([2,0,5,2,0,0]),  # ROOM 3
  Room([0,5,0,0,0,0]),  # ROOM 4
  Room([4,0,0,3,5,13]), # ROOM 5
  Room([0,0,1,0,0,0], False), # ROOM 6 flagged as not updatable
  Room([0,8,0,0,0,0]), # ROOM 7
  Room([7,0,0,0,0,0]), # ROOM 8
  Room([0,9,0,0,0,8]), # ROOM 9
  # etc for the rest of the rooms -
  # note I omitted the initial treasure value since it is always 0
  # I modified the last for statement to account for only 9 rooms

# use random.sample to create random subsets of values and rooms
# - eliminates all the loops and tests
# note this ensures no duplicate treasures (do you want that?)

# create list of 8 random treasure values
values = random.sample(range(10,110),4) + random.sample(range(-4, 0),4)

# create list of 8 randomly selected updatable rooms
roomsToUpdate= random.sample([room for room in rooms if room.updatable], 8)

# update the rooms' Treasures
for room, value in zip(roomsToUpdate, values):

a = range(1,99)
for room in (3,5):
  rooms[room].updateTreasure(100 + random.choice(a))

for room in rooms: print room 
----------------------------- end code -----------------------------

Things I did not do, but suggest:
- store the room destinations in a text file rather than hard-coding 
them in the program. It is almost always a good idea to separate logic 
from data.

 -create a Treasure class, storing instances directly in roo,s rather 
than indexes, and storing treasure definitions in the text file.

-store room instances in the destinations rather than indexes.

At this point you no longer need indexes!

Bob Gailer
919-636-4239 Chapel Hill, NC

More information about the Tutor mailing list