-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
336 lines (294 loc) · 10.5 KB
/
models.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Tuple
from pony.orm import Database
from pony.orm import PrimaryKey, Required, Optional, Set
from pony.orm import db_session
from pony.orm import select
from pony.orm.core import ObjectNotFound, TransactionIntegrityError
from common.helpers import modifier_dictionary, check_formula
db = Database()
class User(db.Entity):
user_id = PrimaryKey(int, auto=False)
chars = Set('Char')
registered = Required(datetime, default=datetime.now)
@classmethod
@db_session
def get_user_by_id(cls, user_id: int):
"""
Should always be used inside handlers instead of User[1234]
"""
try:
return cls[user_id]
except ObjectNotFound:
return cls.register_user(user_id)
@classmethod
def register_user(cls, user_id: int):
"""
Try to make a User with the user_id
"""
with db_session:
try:
user = User(user_id=user_id)
return user
except TransactionIntegrityError:
pass
@db_session
def active_char(self):
"""
Return active char for current user instance
"""
return self.chars.filter(lambda x: x.active).get()
@db_session
def create_char(self, name: str) -> object:
char_exists = self.chars.filter(lambda x: x.name == name).exists()
if char_exists:
raise NameError(
f'You have a char named {name} already'
'Check your charlist with /chars'
)
if len(self.chars) > 5:
raise AssertionError(
'You cannot have more than 5 characters per account. '
)
if name[0].isdigit():
raise ValueError(
'Your char name must not start with a digit.'
)
if len(name) > 20:
raise ValueError(
'Your char name is too long. Max length for names: 20.'
)
newchar = Char(owner=self, name=name, active=False)
self.set_active_char(newchar.name)
return newchar
@db_session
def delete_char(self, name: str) -> bool:
char = self.chars.filter(lambda x: x.name == name).get()
if char:
char.delete()
if self.chars.count():
next_active_char = self.chars.filter().first()
self.set_active_char(next_active_char.name)
else:
raise NameError(
f'You have not a char named {name}. '
'Check your charlist with /chars'
)
@db_session
def set_active_char(self, charname):
"""
Should be used inside try/except. Check that in any case only
one character would be active, safe to use on already active
character.
"""
if not self.chars.count():
raise IndexError('You have not any chars yet.')
char = self.chars.filter(lambda x: x.name == charname).get()
if not char:
raise NameError(
f'You have not a char named {charname}')
if not self.active_char:
char.active = True
else:
for c in self.chars:
c.active = False
char.active = True
class Char(db.Entity):
owner = Required(User)
name = Required(str)
throws = Set('Throw')
attributes = Set('Attribute')
active = Required(bool, default=False)
registered = Required(datetime, default=datetime.now)
@db_session
def throw(self, name: str) -> str:
requested_throw = self.throws.filter(lambda x: x.name == name).get()
if requested_throw:
return requested_throw.formula
else:
return ''
@db_session
def create_throw(self, throw_name: str, formula: str) -> str:
exists = self.throw(throw_name)
if exists:
raise NameError(
f'You have a roll named {throw_name} already')
formula_ok = check_formula(formula)
if formula_ok:
Throw(char=self, name=throw_name, formula=formula)
return True
else:
raise NameError(
f'Formula "{formula}" is invalid or empty. Please check it')
@db_session
def delete_throw(self, throw_name: str):
throw = self.throws.filter(lambda x: x.name == throw_name).get()
if not throw:
raise NameError(
f'Your active char {self.name} has not a roll '
f'named {throw_name}. Please check /chars or ask for /help'
)
throw.delete()
return True
@db_session
def create_attribute(self, name: str, alias: str, value: str,
modifier: str or None = None):
"""
Create an attribute. Note func takes only strings as arguments
"""
common_error_message = (
'Incorrect command. Please check the examples: '
'/addmod Dexterity DEX 20\n'
'/addmod Dexterity DEX 20 5\n'
)
if not all((name, alias, value)):
raise ValueError(common_error_message)
if alias[0].isdigit():
raise ValueError('Alias must not start with a digit!')
if name[0].isdigit():
raise ValueError('Attribute name must not start with a digit!')
if any((len(name) > 25, len(alias) > 8)):
raise ValueError(
'Attribute name or alias are too long.\n'
'Max length for attribute name: 25, '
'Max length for alias: 8'
)
if any((len(name) < 4, len(alias) < 2)):
raise ValueError(
'Attribute name or alias are too short.\n'
'Min length for attribute name: 4, '
'Min length for alias: 2'
)
# existence check
_, name_exists1 = self.get_attribute_by_alias(alias)
name_exists2 = self.get_attribute_by_name(name)
if any([name_exists1, name_exists2]):
raise NameError(
f'Your active char {self.name} has already an attribute '
f'named {name} or attribute alias {alias}. '
'Please check /chars or ask for /help'
)
# values check
try:
value = int(value)
if modifier:
modifier = int(modifier)
else:
modifier = Attribute.get_modifier(value)
except ValueError:
raise ValueError(common_error_message)
else:
Attribute(
char=self, name=name, alias=alias.upper(), value=value,
modifier=modifier
)
@db_session
def delete_attribute(self, name: str):
attr = self.attributes.filter(
lambda x: x.name == name).get()
if not attr:
raise IndexError(
f'Your active char {self.name} has not an '
f'attribute called {name}. '
'Please check /chars or ask for /help'
)
attr.delete()
@db_session
def get_attribute_by_alias(self, alias: str) -> Tuple[int, str]:
attr = self.attributes.filter(
lambda x: x.alias == alias).get()
if attr:
return attr.modifier, attr.name
else:
return None, None
@db_session
def get_attribute_by_name(self, name: str) -> int:
by_name = self.attributes.filter(
lambda x: x.name == name).get()
if by_name:
return by_name.modifier
class Throw(db.Entity):
char = Required(Char)
name = Required(str)
formula = Required(str)
class Attribute(db.Entity):
char = Required(Char)
name = Required(str)
alias = Optional(str)
value = Required(int)
modifier = Optional(int)
@staticmethod
def get_modifier(value: int) -> int:
"""
Get proper modifier for given characteristic value
"""
return modifier_dictionary.get(value, 0)
class Roll(db.Entity):
date = Required(datetime, default=datetime.now)
@classmethod
@db_session
def register(cls):
return cls()
@staticmethod
@db_session
def get_stats():
users_total = select(u for u in User).count()
chars_total = select(ch for ch in Char).count()
new_users_week = select(
u for u in User
if u.registered >= datetime.now() - timedelta(days=7)
).count()
new_chars_week = select(
ch for ch in Char
if ch.registered >= datetime.now() - timedelta(days=7)
).count()
throws_total = select(thr for thr in Throw).count()
attributes_total = select(attr for attr in Attribute).count()
rolls_total = select(roll for roll in Roll).count()
rolls_month = select(
roll for roll in Roll
if roll.date.month == datetime.now().date().month
).count()
rolls_week = select(
roll for roll in Roll
if roll.date >= datetime.now() - timedelta(days=7)
).count()
rolls_today = select(
roll for roll in Roll
if roll.date == datetime.now().date()
).count()
return Statistics(
users_total, chars_total, new_users_week, new_chars_week,
throws_total, attributes_total, rolls_total, rolls_month,
rolls_week, rolls_today)
@dataclass
class Statistics:
users_total: int = 0
chars_total: int = 0
new_users_week: int = 0
new_chars_week: int = 0
throws_total: int = 0
attributes_total: int = 0
rolls_total: int = 0
rolls_month: int = 0
rolls_week: int = 0
rolls_today: int = 0
if __name__ == '__main__':
with db_session:
alex = User(user_id=138946204)
tall = Char(owner=alex, name='Tall', active=True)
dex = Attribute(
char=tall, name='Dexterity', alias='DEX',
value=20, modifier=Attribute.get_modifier(20)
)
throw = Throw(char=tall, name='MyThrow', formula='1d20 + $DEX')
throw2 = Throw(char=tall, name='Wisdom', formula='1d20 2d4 + 3')
alice = Char(owner=alex, name='Alice')
strength = Attribute(
char=alice, name='Strength', alias='STR',
value=15, modifier=Attribute.get_modifier(15)
)
throw3 = Throw(char=alice, name='MyThrow3', formula='1d20 + $DEX')
throw4 = Throw(char=alice, name='Insight', formula='1d20 2d4 + 3')
print('Everything should be commited by now')