dice.py: Factored result printing into main() so that Dice class can be used by other scripts

This commit is contained in:
Anna Rose 2012-03-21 12:18:35 -04:00
parent 83826f9200
commit b04c57ac57

34
dice.py
View File

@ -70,6 +70,7 @@ class Dice():
def roll(self, verbose=False): def roll(self, verbose=False):
results = [] results = []
rerolled = [] rerolled = []
dropped = []
# Roll the actual dice, handling rerolls # Roll the actual dice, handling rerolls
for i in range(0, self.num): for i in range(0, self.num):
@ -91,7 +92,6 @@ class Dice():
if self.drop_low or self.drop_high: if self.drop_low or self.drop_high:
results.sort() results.sort()
dropped = []
if self.drop_low: if self.drop_low:
dropped.extend(results[:self.drop_low]) dropped.extend(results[:self.drop_low])
results = results[self.drop_low:] results = results[self.drop_low:]
@ -105,22 +105,10 @@ class Dice():
# Get the results # Get the results
total = sum(results) + self.mod total = sum(results) + self.mod
if verbose:
drop_info = ''
reroll_info = ''
if dropped:
drop_info = ' [dropped {}]'.format(','.join(['{}'.format(x) for x in dropped]))
if rerolled:
reroll_info = ' [rerolled {}]'.format(','.join(['{}'.format(x) for x in rerolled]))
print('{dice}: {results}{drop}{reroll} {total}'.format(dice=self, results=results, total=total, drop=drop_info, reroll=reroll_info))
else:
print('{dice}: {total}'.format(dice=self, total=total))
self.times_rolled += 1 self.times_rolled += 1
return {'total': total, 'rolls': results, 'dropped': dropped, 'rerolled': rerolled}
def __str__(self): def __str__(self):
reroll_info = '' reroll_info = ''
@ -193,7 +181,21 @@ def main():
for i in range(settings.repeat): for i in range(settings.repeat):
for dice in dice_list: for dice in dice_list:
dice.roll(verbose=settings.verbose) ret = dice.roll()
if settings.verbose:
drop_info = ''
reroll_info = ''
if ret['dropped']:
drop_info = ' [dropped {}]'.format(','.join(['{}'.format(x) for x in ret['dropped']]))
if ret['rerolled']:
reroll_info = ' [rerolled {}]'.format(','.join(['{}'.format(x) for x in ret['rerolled']]))
print('{dice}: {rolls}{drop}{reroll} {total}'.format(dice=dice, rolls=ret['rolls'], total=ret['total'], drop=drop_info, reroll=reroll_info))
else:
print('{dice}: {total}'.format(dice=dice, total=ret['total']))
if __name__ == '__main__': if __name__ == '__main__':