[Tutor] designing POOP
Kent Johnson
kent37 at tds.net
Fri Feb 8 21:24:46 CET 2008
bhaaluu wrote:
> class Explorer(object):
> """player"""
> def __init__(self,name):
> """initilaization method"""
> self.__name = name
> self.strength = 20
> self.wealth = 60
>
> def get_name(self):
> return self.__name
There is no need for get_name(). Just refer to explr.name, the same as
for strength and wealth.
> class Light(object):
> """light switch"""
>
> def __init__(self,light):
> self.light = light
>
> def state(self):
> if self.light == 0:
> print (" IT IS TOO DARK TO SEE ANYTHING")
> else:
> print (" THE LIGHTS ARE ON, BUT NO ONE'S HOME")
show_state() or print_state() might be a better name. If you call this
method __str__() and just return the string instead of printing it, it
will be called when you
print switch
> def cs():
> print "\n"*50
>
> def main():
> tally = 0
> switch = Light(0) #instance
> cs() # clear screen
> name = raw_input(" WHAT IS YOUR NAME, EXPLORER? ")
> explr = Explorer(name)
> while True:
> cs() # clear screen
> print (" %s, YOUR STRENGTH IS %d" % (explr.get_name(), explr.strength))
> print (" YOU HAVE $%d" % explr.wealth)
This could be Explorer.__str__():
def __str__(self):
return " %s, YOUR STRENGTH IS %d\n YOU HAVE $%d" %
(self.get_name(), self.strength, self.wealth)
Then the prints become just
print explr
> switch.state()
> print
> print
> answer = raw_input(" WHAT DO YOU WANT TO DO? [Q|L]: ")
> if answer.upper() == "Q":
> break
> if answer.upper() == "L":
> if switch.light == 1:
> switch.light = 0
> else:
> switch.light = 1
> explr.strength -= 5
> explr.wealth -= 15
> if explr.wealth <= 0:
> print
> print (" YOU HAVE NO MONEY")
> time.sleep(1)
> if explr.strength <= 0:
> print
> print (" YOU DIED...")
> time.sleep(1)
> break
This could be two Explorer methods:
def change_wealth(self, incr):
self.wealth += incr
if self.wealth <= 0:
print
print (" YOU HAVE NO MONEY")
time.sleep(1)
Then call
explr.change_wealth(-15)
Strength is a little trickier because you need to break out of the loop.
You could have
def change_strength(self, incr):
self.strength += incr
if self.strength <= 0:
print
print (" YOU DIED...")
time.sleep(1)
self.alive = False
Then in Explorer.__init__() set
self.alive = True
and change the loop from
while True:
to
while explr.alive:
This would give you an Explorer class that actually does something useful.
Kent
> else:
> print (" INVALID CHOICE")
> tally += 1
> print
> print (" FINAL SCORE:")
> print (" TALLY: %d" % tally)
> print (" STRENGTH: %d" % explr.strength)
> print (" WEALTH: $%d" % explr.wealth)
>
> if __name__ == "__main__":
> main()
>
> Happy Programming!
More information about the Tutor
mailing list