-
Notifications
You must be signed in to change notification settings - Fork 0
/
dice.py
252 lines (187 loc) · 5.35 KB
/
dice.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
from functools import reduce, total_ordering
import random
import sys
@total_ordering
class Dice:
@staticmethod
def parse(s):
s = str(s).replace(' ', '')
if not reduce(lambda a, b: a and (b.isdigit() or b in 'd+-'), s, True):
raise ValueError('invalid Dice string "%s"' % s)
s = s.lower().replace('-', '+-')
fields = [x.strip() for x in s.split('+')]
dice = {}
bonus = 0
for field in fields:
if not field:
continue
if 'd' in field:
(num, sides) = field.split('d')
if num == '-':
num = -1
num = int(num or 1)
sides = int(sides)
Dice.dict_add(dice, sides, num)
else:
bonus += int(field)
return (dice, bonus)
@staticmethod
def dict_add(d, k, v):
if v == 0:
return
if k in d:
d[k] += v
else:
d[k] = v
if d[k] == 0:
del d[k]
@staticmethod
def intify(x):
"""cast floats to ints if they're whole numbers"""
if abs(x - int(x)) < sys.float_info.epsilon:
return int(x)
else:
return x
def __init__(self, s=''):
(self.dice, self.bonus) = Dice.parse(s)
########## Numeric functions ##########
def __add__(self, obj):
if isinstance(obj, int):
return self.__add_int(obj)
elif isinstance(obj, Dice):
return self.__add_dice(obj)
else:
return NotImplemented
def __radd__(self, obj):
if isinstance(obj, int):
return self.__add_int(obj)
else:
return NotImplemented
def __sub__(self, obj):
if isinstance(obj, int):
return self.__add_int(-obj)
elif isinstance(obj, Dice):
return self.__add_dice(-obj)
def __rsub__(self, obj):
if isinstance(obj, int):
return (-self).__add_int(obj)
else:
return NotImplemented
def __mul__(self, obj):
if isinstance(obj, Dice):
obj = obj.as_int(ignore=False)
if isinstance(obj, int):
new = self.copy()
for d in new.dice:
new.dice[d] *= obj
new.bonus *= obj
return new
else:
return NotImplemented
def __rmul__(self, obj):
return self * obj
def __truediv__(self, obj):
if self.dice:
raise ValueError("this Dice isn't just an integer bonus")
if isinstance(obj, Dice):
obj = obj.as_int(ignore=False)
if isinstance(obj, int):
return self.bonus / obj
else:
return NotImplemented
def __rtruediv__(self, obj):
if self.dice:
raise ValueError("this Dice isn't just an integer bonus")
if isinstance(obj, int):
return obj / self.bonus
else:
return NotImplemented
def __neg__(self):
new = self.copy()
new.bonus *= -1
for sides in new.dice:
new.dice[sides] *= -1
return new
def __int__(self):
return self.as_int(ignore=False)
def __float__(self):
return float(int(self))
def __eq__(self, other):
if isinstance(other, Dice):
return self.avg() == other.avg()
elif isinstance(other, int):
return self.avg() == other
return NotImplemented
def __lt__(self, other):
if isinstance(other, Dice):
return self.avg() < other.avg()
elif isinstance(other, int):
return self.avg() < other
return NotImplemented
########## Helper functions ##########
def __add_int(self, i):
dice = self.copy()
dice.bonus += i
return dice
def __add_dice(self, d):
dice = self.copy()
for (sides, num) in d.dice.items():
Dice.dict_add(dice.dice, sides, num)
dice.bonus += d.bonus
return dice
########## Methods ##########
def same(self, other):
if not isinstance(other, Dice):
raise TypeError(
'invalid type %s for Dice.same()' % other.__class__.__name__
)
return str(self) == str(other)
def copy(self):
dice = Dice()
dice.dice = self.dice.copy()
dice.bonus = self.bonus
return dice
def as_int(self, ignore=True):
if not ignore and self.dice:
raise ValueError("this Dice isn't just an integer bonus")
return self.bonus
def as_dice(self, ignore=True):
if not ignore and self.bonus != 0:
raise ValueError("this Dice has a numerical bonus")
return self.copy()
def roll(self):
total = 0
for (sides, num) in self.dice.items():
neg = [1, -1][num < 0]
for i in range(0, num, neg):
total += random.randint(1, sides) * neg
return Dice.intify(total + self.bonus)
def min(self):
pos = [n for n in self.dice.values() if n > 0]
neg = [n * s for (s, n) in self.dice.items() if n < 0]
return sum(pos) + sum(neg) + self.bonus
def avg(self):
avg = 0
for (sides, num) in self.dice.items():
avg += num * (sides + 1) / 2.0
return Dice.intify(avg + self.bonus)
def max(self):
pos = [n * s for (s, n) in self.dice.items() if n > 0]
neg = [n for n in self.dice.values() if n < 0]
return sum(pos) + sum(neg) + self.bonus
def stats(self):
return self.__str__() + ' = %s/%s/%s' % (self.min(), self.avg(), self.max())
def __str__(self):
sides = sorted(
self.dice.items(),
key=lambda x: x[1] * (x[0] + 1) / 2.0,
reverse=True,
)
s = '+'.join(['%sd%s' % (n, s) for (s, n) in sides]).replace('+-', '-')
if self.bonus or not self.dice:
s += '%s%s' % ('+' if self.bonus > 0 else '', self.bonus)
if s.startswith('+'):
return s[1:]
return s
def __repr__(self):
return '<Dice %s>' % str(self)