|
5 | 5 |
|
6 | 6 | Enter what kind and how many dice to roll. The format is the number of
|
7 | 7 | dice, followed by the "d", followed by the number of sides the dice have.
|
8 |
| -You can also add a plus or minus adjustment. |
| 8 | +You can also add a plus, minus, or multiplication adjustment. |
9 | 9 |
|
10 | 10 | Ex:
|
11 | 11 | 3d6 rolls three 6-sided dice
|
12 | 12 | 1d10+2 rolls one 10-sided die, and adds 2
|
13 | 13 | 2d38-1 rolls two 38-sided dice, and subtracts 1
|
| 14 | + 2d20*2 rolls two 20-sided dice, and multiplies the result by 2 |
14 | 15 | QUIT quits the program
|
15 | 16 | ''')
|
16 | 17 |
|
|
36 | 37 | raise Exception('Missing the number of dice.')
|
37 | 38 | numberOfDice = int(numberOfDice)
|
38 | 39 |
|
39 |
| - # Find if there is a plus or minus sign for a modifier: |
40 |
| - modIndex = diceStr.find('+') |
41 |
| - if modIndex == -1: |
42 |
| - modIndex = diceStr.find('-') |
| 40 | + # Find if there is a plus, minus, or multiplication sign for a modifier: |
| 41 | + modIndex = max(diceStr.find('+'), diceStr.find('-'), diceStr.find('*')) |
43 | 42 |
|
44 | 43 | # Find the number of sides. (The "6" in "3d6+1"):
|
45 | 44 | if modIndex == -1:
|
|
53 | 52 | # Find the modifier amount. (The "1" in "3d6+1"):
|
54 | 53 | if modIndex == -1:
|
55 | 54 | modAmount = 0
|
| 55 | + modOperator = None |
56 | 56 | else:
|
57 | 57 | modAmount = int(diceStr[modIndex + 1:])
|
58 |
| - if diceStr[modIndex] == '-': |
59 |
| - # Change the modification amount to negative |
60 |
| - modAmount = -modAmount |
| 58 | + modOperator = diceStr[modIndex] |
61 | 59 |
|
62 | 60 | # Simulate the dice rolls:
|
63 | 61 | rolls = []
|
64 | 62 | for i in range(numberOfDice):
|
65 | 63 | rollResult = random.randint(1, numberOfSides)
|
66 | 64 | rolls.append(rollResult)
|
67 | 65 |
|
| 66 | + # Calculate the total: |
| 67 | + total = sum(rolls) |
| 68 | + if modOperator == '+': |
| 69 | + total += modAmount |
| 70 | + elif modOperator == '-': |
| 71 | + total -= modAmount |
| 72 | + elif modOperator == '*': |
| 73 | + total *= modAmount |
| 74 | + |
68 | 75 | # Display the total:
|
69 |
| - print('Total:', sum(rolls) + modAmount, '(Each die:', end='') |
| 76 | + print('Total:', total, '(Each die:', end=' ') |
70 | 77 |
|
71 | 78 | # Display the individual rolls:
|
72 |
| - for i, roll in enumerate(rolls): |
73 |
| - rolls[i] = str(roll) |
74 |
| - print(', '.join(rolls), end='') |
| 79 | + print(', '.join(map(str, rolls)), end='') |
75 | 80 |
|
76 | 81 | # Display the modifier amount:
|
77 | 82 | if modAmount != 0:
|
78 |
| - modSign = diceStr[modIndex] |
79 |
| - print(', {}{}'.format(modSign, abs(modAmount)), end='') |
| 83 | + print(', {}{}'.format(modOperator, abs(modAmount)), end='') |
80 | 84 | print(')')
|
81 | 85 |
|
82 | 86 | except Exception as exc:
|
|
0 commit comments