David Millar wrote:
> Hello. I'm working on a text adventure game right now, and I seem to be 
> kind of stuck. There's a huge chunk of code called moreaction() that 
> pulls scripted events for certain locations. It's ever-changing so I'm 
> not looking for specifics, but can anyone suggest good ways to clean up 
> or condense the code without sacrificing clarity? The latest version of 
> the source is found at http://thegriddle.net/python/v006.txt Any help is 
> much appreciated :) - Dave M.

One way to help with this is to use functions and a dispatch table. For 
example instead of

     elif lookup == "COVER":
         print "\nYou close the book and stare dumbly at the cover, 
sideways:"
          return
     elif lookup == "TOC":
         print "\nYou glance over the table of contents. You have 
recipes for the following:"
         b = book.keys()
         b.sort()
         for r in b:
             print "*",r,
         print "*"
         return
     elif lookup == "SYRUP":
         print "\n* SYRUP *"
         print "* SYRUP is an interesting drink."
         return

you could write

def cover():
         print "\nYou close the book and stare dumbly at the cover, 
sideways:"

def toc():
         print "\nYou close the book and stare dumbly at the cover, 
sideways:"
          return
     elif lookup == "TOC":
         print "\nYou glance over the table of contents. You have 
recipes for the following:"
         b = book.keys()
         b.sort()
         for r in b:
             print "*",r,
         print "*"

def syrup():
         print "\n* SYRUP *"
         print "* SYRUP is an interesting drink."
         return

dispatch = dict(COVER=cover, TOC=toc, SYRUP=syrup)

fn = dispatch[lookup]
fn()


That is the basic idea. There are a lot of possible complications and 
variations. If some of the functions need arguments, you need to make a 
common protocol for passing arguments and returning values. You might 
want to make the functions methods of a class so they can share state. 
Clever use of introspection can make the dispatch table unnecessary.

You might want to look at the cmd module in the Python standard library 
as an example of this approach.

Kent
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to