Last active
September 21, 2016 06:36
-
-
Save bucho666/4b773063bc610b8ba83941ab3bdcd5b8 to your computer and use it in GitHub Desktop.
Dice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import re | |
import random | |
class Dice(object): | |
def __init__(self, description): | |
self._description = description | |
match = re.search('(\d+)d(\d+)', description) | |
if not match: raise Exception('Dice format error: %s' % description) | |
self._number = int(match.group(1)) | |
self._side = int(match.group(2)) | |
match = re.search('([\+\-]\d+)$', description) | |
self._bonus = int(match.group(1)) if match else 0 | |
def __str__(self): | |
return self._description | |
def roll(self): | |
return sum([random.randint(1, self._side) for n in range(self._number)]) + self._bonus | |
if __name__ == '__main__': | |
import unittest | |
class Test(unittest.TestCase): | |
def testNormal(self): | |
dice = Dice("2d6+4") | |
self.assertEqual(dice._number, 2) | |
self.assertEqual(dice._side, 6) | |
self.assertEqual(dice._bonus, 4) | |
def testMinusBonus(self): | |
dice = Dice("3d7-2") | |
self.assertEqual(dice._number, 3) | |
self.assertEqual(dice._side, 7) | |
self.assertEqual(dice._bonus, -2) | |
def testNoBonus(self): | |
dice = Dice("4d6") | |
self.assertEqual(dice._number, 4) | |
self.assertEqual(dice._side, 6) | |
self.assertEqual(dice._bonus, 0) | |
def testBigDice(self): | |
dice = Dice("42d256+512") | |
self.assertEqual(dice._number, 42) | |
self.assertEqual(dice._side, 256) | |
self.assertEqual(dice._bonus, 512) | |
def testRoll(self): | |
self.roll10Test("1d6") | |
self.roll10Test("2d6") | |
self.roll10Test("3d6") | |
def testMaxMin(self): | |
self.assertTrue(self.waitRoll("1d6", 1)) | |
self.assertTrue(self.waitRoll("1d6", 6)) | |
self.assertTrue(self.waitRoll("1d6+1", 7)) | |
self.assertTrue(self.waitRoll("2d6", 2)) | |
self.assertTrue(self.waitRoll("2d6", 12)) | |
self.assertTrue(self.waitRoll("2d6+4", 16)) | |
def testIgnoreFormat(self): | |
self.assertRaises(Exception, Dice, 'd6') | |
def waitRoll(self, dice, roll): | |
d = Dice(dice) | |
while True: | |
if d.roll() != roll: continue | |
return True | |
def roll10Test(self, desc): | |
print desc | |
d = Dice(desc) | |
print [d.roll() for n in range(10)] | |
def testString(self): | |
self.stringTest('1d6-2') | |
self.stringTest('2d3+2') | |
self.stringTest('3d6') | |
def stringTest(self, desc): | |
self.assertEqual(str(Dice(desc)), desc) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment