[Tutor] >> BANANAS! << The answer. :-)

D-Man dsh8290@rit.edu
Fri, 9 Mar 2001 10:49:22 -0500


On Fri, Mar 09, 2001 at 07:19:58AM -0800, Chris McCormick wrote:
| 
|    So, can you have a "significant rewrite" of a program that's fewer
|    than 1000 lines? I got the chance yesterday to play with my virtual

Yes.

|    As usual, I have a piggyback question:
|    
|    I'm always trying to pass information from my main module, game.py, to
|    functions contained in other modules. Those functions need to update
|    the information so that it can be passed again on the next loop. The
|    problem I have is making the information available to everyone. The
|    best solution I have come up with so far is to have a "globals"
|    dictionary, and pass it as an argument to the functions, like so:

I would recommend using a class.  A class is essentially some
functions bundled together with some data they operate on.  For
example:

######## module Banana.py

class Banana :
    def __init__( self ) :
        self.current_age = 0 # it start out new right?
        self.ripeness = 0
        self.is_bad = 0      # I miss the keyword 'false'
        self.is_eaten = 0

    def mature( self ) :
        self.ripeness += 1 
        # the += operator only works in >= 2.0
        # otherwise use
        ## self.ripeness = self.ripeness + 1

You should be able to get rid of that 'globals' dictionary.  You
commented it as "contain needed info".  That's exactly what classes
are for.

If you want the count of bananas, use len( bananas_dict.keys() ).


|    Is there *any* way to make a dictionary or a list global to *all*
|    modules, or to make it importable? On a general level, what's the best

It is importable.  In  window.py put

import game


then use

game.globals

to access it.

|    treatment of scope you've read? 90% of my problems arise from
|    confusion about scope.

Read the part of the tutorial/reference about classes.  I think they
will help you a lot.  Do you have experience programming in other
languages?  Data encapsulation is what you need.  You have a good idea
of what you want to do, and python likes encapsulation much more than
C does.  In C, for example, everything exists in 1 namespace (except
for locals in a function).  Thus you get a higher tendency to use globals in
C.  Python makes it much harder to use globals and helps you to
explore ways to encapsulate your data more.

|    Thanks for listening to me ramble, Chris

No problem.  If you don't know or understand classes/OOP feel free to
ask and someone (maybe even me ;-)) will come up with a good
introduction with examples, etc.

-D