[OT] Re: Old Paranoia Game in Python
Steven Bethard
steven.bethard at gmail.com
Mon Jan 10 16:48:50 EST 2005
Terry Reedy wrote:
> Never saw this specific game. Some suggestions on additional factoring out
> of duplicate code.
>
>
>>def next_page(this_page):
>> print "\n"
>> if this_page == 0:
>> page = 0
>> return
>
>
> The following elif switch can be replaced by calling a selection from a
> list of functions:
>
> [None, page1, pag2, ... page57][this_page]()
>
>
>> elif this_page == 1:
>> page1()
>> return
>> elif this_page == 2:
>> page2()
>> return
>
> ...
>
>> elif this_page == 57:
>> page57()
>> return
>
>
> Also, a chose3 function to complement your chose (chose2) function would
> avoid repeating the choose-from-3 code used on multiple pages.
>
> Terry J. Reedy
This is what I love about this list. Where else is someone going to
look at 1200+ lines of code and give you useful advice?! ;) Very cool.
(Thanks Terry!)
While we're making suggestions, you might consider writing dice_roll as:
def dice_roll(num, sides):
return sum(random.randrange(sides) for _ in range(num)) + num
for Python 2.4 or
def dice_roll(num, sides):
return sum([random.randrange(sides) for _ in range(num)]) + num
for Python 2.3.
You also might consider writing all the pageX methods in a class, so all
your globals can be accessed through self, e.g.:
class Game(object):
def __init__(self):
...
self.page = 1
self.computer_request = 0
...
def page2():
print ...
if self.computer_request == 1:
new_clone(45)
else:
new_clone(32)
...
You could then have your class implement the iteration protocol:
def __iter__(self):
try:
while True:
self.old_page = self.page
yield getattr(self, "page%i" % page)
except AttributeError:
raise StopIteration
And then your main could look something like:
def main(args):
...
instructions()
more()
character()
more()
for page_func in Game():
page_func()
print "-"*79
Anyway, cool stuff. Thanks for sharing!
Steve
More information about the Python-list
mailing list