-
Notifications
You must be signed in to change notification settings - Fork 1
/
CortexPal.py
1636 lines (1411 loc) · 64.6 KB
/
CortexPal.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from endpoints import Controller, AccessDenied
from discord_interactions import verify_key, InteractionType, InteractionResponseType
import requests
import logging
import json
import configparser
import sqlite3
import random
import os
import traceback
import re
import uuid
from datetime import date, datetime, timedelta, timezone
MESSAGE_URL = 'https://discord.com/api/v9/channels/{0}/messages'
PATCH_URL = 'https://discord.com/api/v9/channels/{0}/messages/{1}'
PIN_URL = 'https://discord.com/api/v9/channels/{0}/pins/{1}'
UNPIN_URL = 'https://discord.com/api/v9/channels/{0}/pins/{1}'
DICE_EXPRESSION = re.compile('(\d*(d|D))?(4|6|8|10|12)')
DIE_SIZES = [4, 6, 8, 10, 12]
UNTYPED_STRESS = 'General'
DIE_FACE_ERROR = '{0} is not a valid die size. You may only use dice with sizes of 4, 6, 8, 10, or 12.'
DIE_STRING_ERROR = '{0} is not a valid die or dice.'
DIE_EXCESS_ERROR = 'You can\'t use that many dice.'
DIE_MISSING_ERROR = 'There were no valid dice in that command.'
DIE_LACK_ERROR = 'That pool only has {0}D{1}.'
DIE_NONE_ERROR = 'That pool doesn\'t have any D{0}s.'
DIE_MAX_ERROR = 'You can\'t step up a die past D12.'
NOT_EXIST_ERROR = 'There\'s no such {0} yet.'
HAS_NONE_ERROR = '{0} doesn\'t have any {1}.'
HAS_ONLY_ERROR = '{0} only has {1} {2}.'
INSTRUCTION_ERROR = '`{0}` is not a valid instruction for the `{1}` command.'
UNKNOWN_COMMAND_ERROR = 'That\'s not a valid command.'
JOIN_ERROR = 'The #{0} channel does not allow other channels to join. Future commands apply only to this channel.'
UNEXPECTED_ERROR = 'Oops. A software error interrupted this command.'
LOW_NUMBER_ERROR = '{0} must be greater than zero.'
BEST_OPTION = 'best'
JOIN_OPTION = 'join'
GAME_INFO_HEADER = '**Cortex Game Information**'
HELP_TEXT = (
'```CortexPal2000 v1.0.0: a Discord bot for Cortex Prime RPG players.\n'
'asset Adjust assets.\n'
'clean Reset all game data for a channel.\n'
'comp Adjust complications.\n'
'dist Adjust distinctions.\n'
'info Display all game information.\n'
'option Change the bot\'s optional behavior.\n'
'pin Pin a message to the channel to hold game information.\n'
'pool Adjust dice pools.\n'
'pp Adjust plot points.\n'
'report Report the bot\'s statistics.\n'
'roll Roll some dice.\n'
'stress Adjust stress.\n'
'xp Award experience points.\n'
'help Provides command hints.\n'
'Also try using help to show hints for specific commands (like /help command:asset).'
'\n'
'For more information about this project: https://github.com/dbisdorf/cortex-discord-2```'
)
ASSET_HELP_TEXT = (
'```Adjust assets.\n'
'\n'
'For example:\n'
'/asset add who:anne what:big wrench die:6 (gives Anne a D6 Big Wrench asset)\n'
'/asset stepup who:beth what:fast car (steps up Beth\'s Fast Car asset)\n'
'/asset stepdown who:cat what:nice outfit steps:2 (steps down Cat\'s Nice Outfit asset twice)\n'
'/asset remove who:dora what:jetpack (removes Dora\'s Jetpack asset)```'
)
CLEAN_HELP_TEXT = (
'```Reset all game data for a channel.```'
)
COMP_HELP_TEXT = (
'```Adjust complications.\n'
'\n'
'For example:\n'
'/comp add who:anne what:cloud of smoke die:6 (gives Anne a D6 Cloud Of Smoke complication)\n'
'/comp stepup who:beth what:confused (steps up Beth\'s Confused complication)\n'
'/comp stepdown who:cat what:dazed steps:2 (steps down Cat\'s Dazed complication twice)\n'
'/comp remove who:dora what:sun in your eyes (removes Dora\'s Sun In Your Eyes complication)```'
)
DIST_HELP_TEXT = (
'```Adjust distinctions.\n'
'\n'
'For example:\n'
'/dist add who:anne what:stubborn (gives Ann a Stubborn distinction)\n'
'/dist add who:beth what:honorable knight die:6 (gives Beth a D6 Honorable Knight distinction)\n'
'/dist remove who:scene what:foggy (remove the Foggy distinction from the scene)\n```'
)
INFO_HELP_TEXT = (
'```Display all game information.```'
)
OPTION_HELP_TEXT = (
'```Change the bot\'s optional behavior.\n'
'\n'
'For example:\n'
'/option best switch:on (turn on suggestions for best total and effect)\n'
'/option best switch:off (turn off suggestions for best total and effect)\n'
'/option join switch:on (allow other channels to join this channel)\n'
'/option join switch:off (break and prohibit joins between this channel and other channels)\n'
'/option join channel:other-channel (all commands from this channel apply to the game in #other-channel)```'
)
PIN_HELP_TEXT = (
'```Pin a message to the channel to hold game information.```'
)
POOL_HELP_TEXT = (
'```Adjust dice pools.\n'
'\n'
'For example:\n'
'/pool add name:doom dice:6 2d8 (gives the Doom pool a D6 and 2D8)\n'
'/pool remove name:doom dice:10 (spends a D10 from the Doom pool)\n'
'/pool stepup name:doom die:8 (steps up a D8 in the pool to D10)\n'
'/pool stepdown name:doom die:12 steps:3 (steps down a D12 in the pool to D6)\n'
'/pool roll name:doom (rolls the Doom pool)\n'
'/pool roll name:doom dice:2d6 10 (rolls the Doom pool and adds 2D6 and a D10)\n'
'/pool roll name:doom keep:3 (rolls the Doom pool and keeps three dice for the total)\n'
'/pool clear name:doom (clears the entire Doom pool)\n'
'The "keep" option only functions if you\'ve used the "/option" command to tell the bot\n'
'to suggest the best total and effect dice.\n'
'\n'
'When rolling a pool and adding dice, you may include your trait names.\n'
'The command will ignore any words that don\'t look like dice.\n'
'\n'
'For example:\n'
'/pool roll name:doom dice:D6 Mind D10 Pirate (adds D6 and D10 to the pool when rolling)```'
)
PP_HELP_TEXT = (
'```Adjust plot points.\n'
'\n'
'For example:\n'
'/pp add who:alice number:3 (gives Alice 3 plot points)\n'
'/pp remove who:alice (spends one of Alice\'s plot points)\n'
'/pp remove who:alice number:6 (spends six of Alice\'s plot points)\n'
'/pp clear who:alice (clears Alice from plot point lists)```'
)
REPORT_HELP_TEXT = (
'```Report the bot\'s statistics.```'
)
ROLL_HELP_TEXT = (
'```Roll some dice.\n'
'\n'
'For example:\n'
'/roll dice:12 (rolls a D12)\n'
'/roll dice:4 3d8 10 10 (rolls a D4, 3D8, and 2D10)\n'
'/roll dice:6 6 6 8 8 keep:3 (rolls 3D6 and 2D8 and keeps the best three for the total)\n'
'The "keep" option only functions if you\'ve used the "/option" command to tell the bot\n'
'to suggest the best total and effect dice.\n'
'\n'
'You may include your trait names. The command will ignore any words that don\'t look like dice.\n'
'\n'
'For example:\n'
'/roll D6 Mind D10 Navigation D6 Pirate (rolls 2D6 and a D10, ignoring the trait names)```'
)
STRESS_HELP_TEXT = (
'```Adjust stress.\n'
'\n'
'For example:\n'
'/stress add who:amy die:8 (gives Amy D8 general stress)\n'
'/stress add who:ben what:mental die:6 (gives Ben D6 Mental stress)\n'
'/stress stepup who:cat what:social (steps up Cat\'s Social stress)\n'
'/stress stepdown who:doe what:physical steps:2 (steps down Doe\'s Physical stress twice)\n'
'/stress remove who:eve what:psychic (removes Eve\'s Psychic stress)\n'
'/stress clear who:fin (clears all of Fin\'s stress)```'
)
XP_HELP_TEXT = (
'```Award experience points.\n'
'\n'
'For example:\n'
'/xp add who:alice number:3 (gives Alice 3 experience points)\n'
'/xp remove who:alice (spends one of Alice\'s experience points)\n'
'/xp remove who:alice number:5 (spends five of Alice\'s experience points)\n'
'/xp clear alice (clears Alice from experience point lists)```'
)
# Read configuration.
config = configparser.ConfigParser()
config.read('cortexpal.ini')
auth_request_headers = {
"Authorization": "Bot {}".format(config['discord']['token'])
}
# Set up logging.
#logger = logging.getLogger(__name__)
# Classes and functions follow.
class DiscordResponse:
elements = {}
def __init__(self, text):
self.elements['type'] = InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE
self.elements['data'] = {'content': str(text)}
def json(self):
return self.elements
class DiscordResponsePong(DiscordResponse):
def __init__(self):
self.elements['type'] = InteractionResponseType.PONG
class CortexError(Exception):
"""Exception class for command and rules errors specific to this bot."""
def __init__(self, message, *args):
self.message = message
self.args = args
def __str__(self):
return self.message.format(*(self.args))
def parse_string_into_dice(words):
"""Examine the words of an input string, and keep those that are dice notations."""
dice = []
for word in words.split(' '):
if DICE_EXPRESSION.fullmatch(word):
dice.append(Die(word))
return dice
def capitalize_words(words):
"""Capitalize the words of an input string."""
capitalized = []
for word in words.split(' '):
capitalized.append(word.lower().capitalize())
return ' '.join(capitalized)
def convert_to_capitals_and_dice(words):
"""Given a string of words, either capitalize the words or turn them into die notations."""
converted = []
for word in words.split(' '):
if DICE_EXPRESSION.fullmatch(word):
numbers = word.lower().split('d')
if len(numbers) == 1:
converted.append('D{0}'.format(numbers[0]))
else:
converted.append('{0}D{1}'.format(numbers[0], numbers[1]))
else:
converted.append(word.lower().capitalize())
return ' '.join(converted)
def fetch_all_dice_for_parent(db_parent):
"""Given an object from the database, get all the dice that belong to it."""
dice = []
db_parent.cursor.execute('SELECT * FROM DIE WHERE PARENT_GUID=:PARENT_GUID', {'PARENT_GUID':db_parent.db_guid})
fetching = True
while fetching:
row = db_parent.cursor.fetchone()
if row:
die = Die(name=row['NAME'], size=row['SIZE'], qty=row['QTY'])
die.already_in_db(db_parent.db, db_parent, row['GUID'])
dice.append(die)
else:
fetching = False
return dice
def list_of_dice(dice):
return ' '.join([d.output() for d in dice if d])
class Die:
"""A single die, or a set of dice of the same size."""
def __init__(self, expression=None, name=None, size=4, qty=1):
self.name = name
self.size = size
self.qty = qty
self.db_parent = None
self.db_guid = None
self.db = None
self.cursor = None
if expression:
if not DICE_EXPRESSION.fullmatch(expression):
raise CortexError(DIE_STRING_ERROR, expression)
numbers = expression.lower().split('d')
if len(numbers) == 1:
self.size = int(numbers[0])
else:
if numbers[0]:
self.qty = int(numbers[0])
self.size = int(numbers[1])
def store_in_db(self, db, db_parent):
"""Store this die in the database, under a given parent."""
self.db = db
self.cursor = self.db.cursor()
self.db_parent = db_parent
self.db_guid = uuid.uuid1().hex
self.cursor.execute('INSERT INTO DIE (GUID, NAME, SIZE, QTY, PARENT_GUID) VALUES (?, ?, ?, ?, ?)', (self.db_guid, self.name, self.size, self.qty, self.db_parent.db_guid))
self.db.commit()
def already_in_db(self, db, db_parent, db_guid):
"""Inform the Die that it is already in the database, under a given parent and guid."""
self.db = db
self.cursor = self.db.cursor()
self.db_parent = db_parent
self.db_guid = db_guid
def remove_from_db(self):
"""Remove this Die from the database."""
if self.db_guid:
self.cursor.execute('DELETE FROM DIE WHERE GUID=:guid', {'guid':self.db_guid})
self.db.commit()
def step_down(self, steps=1):
"""Step down the die size."""
new_size = max(4, self.size - (2 * steps))
if self.size != new_size:
self.update_size(new_size)
def step_up(self, steps=1):
"""Step up the die size."""
new_size = min(12, self.size + (2 * steps))
if self.size != new_size:
self.update_size(new_size)
def combine(self, other_die):
"""Combine this die with another die (as when applying a new stress die to existing stress)."""
if self.size < other_die.size:
self.update_size(other_die.size)
elif self.size < 12:
self.update_size(self.size + 2)
def update_size(self, new_size):
"""Change the size of the die."""
self.size = new_size
if self.db_guid:
self.cursor.execute('UPDATE DIE SET SIZE=:size WHERE GUID=:guid', {'size':self.size, 'guid':self.db_guid})
self.db.commit()
def update_qty(self, new_qty):
"""Change the quantity of the dice."""
self.qty = new_qty
if self.db_guid:
self.cursor.execute('UPDATE DIE SET QTY=:qty WHERE GUID=:guid', {'qty':self.qty, 'guid':self.db_guid})
self.db.commit()
def is_max(self):
"""Identify whether the Die is at the maximum allowed size."""
return self.size == 12
def output(self):
"""Return the Die as a string suitable for output in Discord."""
return str(self)
def __str__(self):
"""General purpose string representation of the Die."""
if self.qty > 1:
return '{0}D{1}'.format(self.qty, self.size)
else:
return 'D{0}'.format(self.size)
class NamedDice:
"""A collection of user-named single-die traits, suitable for complications and assets."""
def __init__(self, db, category, group, db_parent, db_guid=None):
self.db = db
self.cursor = db.cursor()
self.dice = {}
self.category = category
self.group = group
self.db_parent = db_parent
if db_guid:
self.db_guid = db_guid
else:
if self.group:
self.cursor.execute('SELECT * FROM DICE_COLLECTION WHERE PARENT_GUID=:PARENT_GUID AND CATEGORY=:category AND GRP=:group', {'PARENT_GUID':self.db_parent.db_guid, 'category':self.category, 'group':self.group})
else:
self.cursor.execute('SELECT * FROM DICE_COLLECTION WHERE PARENT_GUID=:PARENT_GUID AND CATEGORY=:category AND GRP IS NULL', {'PARENT_GUID':self.db_parent.db_guid, 'category':self.category})
row = self.cursor.fetchone()
if row:
self.db_guid = row['GUID']
else:
self.db_guid = uuid.uuid1().hex
self.cursor.execute('INSERT INTO DICE_COLLECTION (GUID, CATEGORY, GRP, PARENT_GUID) VALUES (?, ?, ?, ?)', (self.db_guid, self.category, self.group, self.db_parent.db_guid))
self.db.commit()
fetched_dice = fetch_all_dice_for_parent(self)
for die in fetched_dice:
self.dice[die.name] = die
def remove_from_db(self):
"""Remove these NamedDice from the database."""
for name in list(self.dice):
self.dice[name].remove_from_db()
self.cursor.execute("DELETE FROM DICE_COLLECTION WHERE GUID=:db_guid", {'db_guid':self.db_guid})
self.db.commit()
self.dice = {}
def is_empty(self):
"""Identify whether there are any dice in this object."""
return not self.dice
def add(self, name, die):
"""Add a new die, with a given name."""
die.name = name
if not name in self.dice:
die.store_in_db(self.db, self)
self.dice[name] = die
return 'New {0}: {1}'.format(self.category, self.output(name))
elif self.dice[name].is_max():
return 'This would step up the {0} beyond {1}.'.format(self.category, self.output(name))
else:
self.dice[name].combine(die)
return 'Raised to ' + self.output(name)
def remove(self, name):
"""Remove a die with a given name."""
if not name in self.dice:
raise CortexError(NOT_EXIST_ERROR, self.category)
output = 'Removed {0}: {1}'.format(self.category, self.output(name))
self.dice[name].remove_from_db()
del self.dice[name]
return output
def step_up(self, name, steps=1):
"""Step up the die with a given name."""
if not name in self.dice:
raise CortexError(NOT_EXIST_ERROR, self.category)
if self.dice[name].is_max():
return 'This would step up the {0} beyond {1}.'.format(self.category, self.output(name))
self.dice[name].step_up(steps)
return 'Stepped up {0} to {1}.'.format(self.category, self.output(name))
def step_down(self, name, steps=1):
"""Step down the die with a given name."""
if not name in self.dice:
raise CortexError(NOT_EXIST_ERROR, self.category)
if self.dice[name].size - (steps * 2) < 4:
self.remove(name)
return 'Stepped down and removed {0}: {1}.'.format(self.category, name)
else:
self.dice[name].step_down(steps)
return 'Stepped down {0} to {1}.'.format(self.category, self.output(name))
def get_all_names(self):
"""Identify the names of all the dice in this object."""
return list(self.dice)
def output(self, name):
"""For a die of a given name, return a formatted description of that die."""
return '{0} {1}'.format(self.dice[name].output(), name)
def output_all(self, separator='\n'):
"""Return a formatted description of all the dice in this object."""
output = ''
prefix = ''
for name in list(self.dice):
output += prefix + self.output(name)
prefix = separator
return output
class DicePool:
"""A single-purpose collection of die sizes and quantities, suitable for doom pools, crisis pools, and growth pools."""
def __init__(self, group, incoming_dice=[]):
self.group = group
self.dice = [None, None, None, None, None]
self.db_parent = None
self.db_guid = None
if incoming_dice:
self.add(incoming_dice)
def store_in_db(self, db, db_parent):
"""Store this pool in the database."""
self.db = db
self.cursor = db.cursor()
self.db_guid = uuid.uuid1().hex
self.db_parent = db_parent
self.cursor.execute("INSERT INTO DICE_COLLECTION (GUID, CATEGORY, GRP, PARENT_GUID) VALUES (?, 'pool', ?, ?)", (self.db_guid, self.group, self.db_parent.db_guid))
self.db.commit()
def already_in_db(self, db, db_parent, db_guid):
"""Inform the pool that it is already in the database, under a given parent and guid."""
self.db = db
self.cursor = db.cursor()
self.db_parent = db_parent
self.db_guid = db_guid
def fetch_dice_from_db(self):
"""Get all the dice from the database that would belong to this pool."""
fetched_dice = fetch_all_dice_for_parent(self)
for die in fetched_dice:
self.dice[DIE_SIZES.index(die.size)] = die
def disconnect_from_db(self):
"""Prevent further changes to this pool from affecting the database."""
self.db_parent = None
self.db_guid = None
def is_empty(self):
"""Identify whether this pool is empty."""
return not self.dice
def remove_from_db(self):
"""Remove this entire pool from the database."""
for index in range(len(self.dice)):
if self.dice[index]:
self.dice[index].remove_from_db()
self.cursor.execute("DELETE FROM DICE_COLLECTION WHERE GUID=:db_guid", {'db_guid':self.db_guid})
self.db.commit()
self.dice = [None, None, None, None, None]
def add(self, dice):
"""Add dice to the pool."""
for die in dice:
index = DIE_SIZES.index(die.size)
if self.dice[index]:
self.dice[index].update_qty(self.dice[index].qty + die.qty)
else:
self.dice[index] = die
if self.db_parent and not die.db_parent:
die.store_in_db(self.db, self)
return '{0} (added {1})'.format(self.output(), list_of_dice(dice))
def remove(self, dice):
"""Remove dice from the pool."""
for die in dice:
index = DIE_SIZES.index(die.size)
if self.dice[index]:
stored_die = self.dice[index]
if die.qty > stored_die.qty:
raise CortexError(DIE_LACK_ERROR, stored_die.qty, stored_die.size)
stored_die.update_qty(stored_die.qty - die.qty)
if stored_die.qty == 0:
if self.db_parent:
stored_die.remove_from_db()
self.dice[index] = None
else:
raise CortexError(DIE_NONE_ERROR, die.size)
return '{0} (removed {1})'.format(self.output(), list_of_dice(dice))
def step_up(self, die, steps=1):
"""Step up a die in the pool."""
if die.size + (steps * 2) > 12:
raise CortexError(DIE_MAX_ERROR)
else:
self.remove([die])
new_die = Die(size=die.size)
new_die.step_up(steps)
self.add([new_die])
return '{0} (stepped up {1} to {2})'.format(self.output(), die, new_die)
def step_down(self, die, steps=1):
"""Step down a die in the pool."""
self.remove([die])
if die.size - (steps * 2) >= 4:
new_die = Die(size=die.size)
new_die.step_down(steps)
self.add([new_die])
return '{0} (stepped down {1} to {2})'.format(self.output(), die, new_die)
else:
return '{0} (stepped down and removed {1})'.format(self.output(), die)
def temporary_copy(self):
"""Return a temporary, non-persisted copy of this dice pool."""
copy = DicePool(self.group)
dice_copies = []
for die in self.dice:
if die:
dice_copies.append(Die(size=die.size, qty=die.qty))
copy.add(dice_copies)
return copy
def roll(self, roller, suggest_best=None):
"""Roll all the dice in the pool, and return a formatted summary of the results."""
output = ''
separator = ''
rolls = []
for die in self.dice:
if die:
output += '{0}D{1} : '.format(separator, die.size)
for num in range(die.qty):
roll = {'value': roller.roll(die.size), 'size': die.size}
roll_str = str(roll['value'])
if roll_str == '1':
roll_str = '**(1)**'
else:
rolls.append(roll)
output += roll_str + ' '
separator = '\n'
if suggest_best:
if len(rolls) == 0:
output += '\nBotch!'
else:
# Calculate best total, then choose an effect die
rolls.sort(key=lambda roll: roll['value'], reverse=True)
if len(rolls) > suggest_best:
best_total_dice = rolls[:suggest_best]
best_effect_dice = sorted(rolls[suggest_best:], key=lambda roll: roll['size'], reverse=True)
best_effect_1 = 'D{0}'.format(best_effect_dice[0]['size'])
else:
best_total_dice = rolls
best_effect_1 = 'D4'
best_total_addition = ' + '.join([str(d['value']) for d in best_total_dice])
best_total_1 = sum([d['value'] for d in best_total_dice])
output += '\nBest Total: {0} ({1}) with Effect: {2}'.format(best_total_1, best_total_addition, best_effect_1)
# Find best effect die, then chooose best total
if len(rolls) > suggest_best:
rolls.sort(key=lambda roll: roll['value'])
rolls.sort(key=lambda roll: roll['size'], reverse=True)
best_effect_2 = 'D{0}'.format(rolls[0]['size'])
resorted_rolls = sorted(rolls[1:], key=lambda roll: roll['value'], reverse=True)
best_total_dice = resorted_rolls[:suggest_best]
else:
rolls.sort(key=lambda roll: roll['value'])
best_total_dice = rolls
best_effect_2 = 'D4'
best_total_addition = ' + '.join([str(d['value']) for d in best_total_dice])
best_total_2 = sum([d['value'] for d in best_total_dice])
"""
best_total_2 = rolls[0]['value']
best_addition_2 = '{0}'.format(rolls[0]['value'])
best_effect_2 = 'D4'
if len(rolls) > 1:
best_total_2 += rolls[1]['value']
best_addition_2 = '{0} + {1}'.format(best_addition_2, rolls[1]['value'])
if len(rolls) > 2:
best_effect_2 = 'D{0}'.format(rolls[0]['size'])
resorted_rolls = sorted(rolls[1:], key=lambda roll: roll['value'], reverse=True)
best_total_2 = resorted_rolls[0]['value'] + resorted_rolls[1]['value']
best_addition_2 = '{0} + {1}'.format(resorted_rolls[0]['value'], resorted_rolls[1]['value'])
"""
if best_effect_1 != best_effect_1 or best_total_1 != best_total_2:
output += ' | Best Effect: {0} with Total: {1} ({2})'.format(best_effect_2, best_total_2, best_total_addition)
return output
def output(self):
"""Return a formatted list of the dice in this pool."""
if self.is_empty():
return 'empty'
"""
output = ''
for die in self.dice:
if die:
output += die.output() + ' '
"""
return list_of_dice(self.dice)
class DicePools:
"""A collection of DicePool objects."""
def __init__(self, db, db_parent):
self.db = db
self.cursor = db.cursor()
self.pools = {}
self.db_parent = db_parent
self.cursor.execute('SELECT * FROM DICE_COLLECTION WHERE CATEGORY="pool" AND PARENT_GUID=:PARENT_GUID', {'PARENT_GUID':self.db_parent.db_guid})
pool_info = []
fetching = True
while fetching:
row = self.cursor.fetchone()
if row:
pool_info.append({'db_guid':row['GUID'], 'grp':row['GRP'], 'parent_guid':row['PARENT_GUID']})
else:
fetching = False
for fetched_pool in pool_info:
new_pool = DicePool(fetched_pool['grp'])
new_pool.already_in_db(self.db, fetched_pool['parent_guid'], fetched_pool['db_guid'])
new_pool.fetch_dice_from_db()
self.pools[new_pool.group] = new_pool
def is_empty(self):
"""Identify whether we have any pools."""
return not self.pools
def remove_from_db(self):
"""Remove all of these pools from the database."""
for group in list(self.pools):
self.pools[group].remove_from_db()
self.pools = {}
def add(self, group, dice):
"""Add some dice to a pool under a given name."""
if not group in self.pools:
self.pools[group] = DicePool(group)
self.pools[group].store_in_db(self.db, self.db_parent)
self.pools[group].add(dice)
return '{0}: {1} (added {2})'.format(group, self.pools[group].output(), list_of_dice(dice))
def remove(self, group, dice):
"""Remove some dice from a pool with a given name."""
if not group in self.pools:
raise CortexError(NOT_EXIST_ERROR, 'pool')
self.pools[group].remove(dice)
return '{0}: {1} (removed {2})'.format(group, self.pools[group].output(), list_of_dice(dice))
def step_up(self, group, die, steps=1):
"""Step up a die in a pool with a given name."""
if not group in self.pools:
raise CortexError(NOT_EXIST_ERROR, 'pool')
output = self.pools[group].step_up(die, steps)
return '{0}: {1}'.format(group, output)
def step_down(self, group, die, steps=1):
"""Step down a die in a pool with a given name."""
if not group in self.pools:
raise CortexError(NOT_EXIST_ERROR, 'pool')
output = self.pools[group].step_down(die, steps)
return '{0}: {1}'.format(group, output)
def clear(self, group):
"""Remove one entire pool."""
if not group in self.pools:
raise CortexError(NOT_EXIST_ERROR, 'pool')
self.pools[group].remove_from_db()
del self.pools[group]
return 'Cleared {0} pool.'.format(group)
def temporary_copy(self, group):
"""Return an independent, non-persistent copy of a pool."""
if not group in self.pools:
raise CortexError(NOT_EXIST_ERROR, 'pool')
return self.pools[group].temporary_copy()
def roll(self, group, suggest_best=False):
"""Roll all the dice in a certain pool and return the results."""
return self.pools[group].roll(suggest_best)
def output(self):
"""Return a formatted summary of all the pools in this object."""
output = ''
prefix = ''
for key in list(self.pools):
output += '{0}*{1}*: {2}'.format(prefix, key, self.pools[key].output())
prefix = '\n'
return output
class Resources:
"""Holds simple quantity-based resources, like plot points."""
def __init__(self, db, category, db_parent):
self.db = db
self.cursor = db.cursor()
self.resources = {}
self.category = category
self.db_parent = db_parent
self.cursor.execute("SELECT * FROM RESOURCE WHERE PARENT_GUID=:PARENT_GUID AND CATEGORY=:category", {'PARENT_GUID':self.db_parent.db_guid, 'category':self.category})
fetching = True
while fetching:
row = self.cursor.fetchone()
if row:
self.resources[row['NAME']] = {'qty':row['QTY'], 'db_guid':row['GUID']}
else:
fetching = False
def is_empty(self):
"""Identify whether there are any resources stored here."""
return not self.resources
def remove_from_db(self):
"""Removce these resources from the database."""
self.cursor.executemany("DELETE FROM RESOURCE WHERE GUID=:db_guid", [{'db_guid':self.resources[resource]['db_guid']} for resource in list(self.resources)])
self.db.commit()
self.resources = {}
def add(self, name, qty=1):
"""Add a quantity of resources to a given name."""
if not name in self.resources:
db_guid = uuid.uuid1().hex
self.resources[name] = {'qty':qty, 'db_guid':db_guid}
self.cursor.execute("INSERT INTO RESOURCE (GUID, CATEGORY, NAME, QTY, PARENT_GUID) VALUES (?, ?, ?, ?, ?)", (db_guid, self.category, name, qty, self.db_parent.db_guid))
self.db.commit()
else:
self.resources[name]['qty'] += qty
self.cursor.execute("UPDATE RESOURCE SET QTY=:qty WHERE GUID=:db_guid", {'qty':self.resources[name]['qty'], 'db_guid':self.resources[name]['db_guid']})
self.db.commit()
return self.output(name)
def remove(self, name, qty=1):
"""Remove a quantity of resources from a given name."""
if not name in self.resources:
raise CortexError(HAS_NONE_ERROR, name, self.category)
if self.resources[name]['qty'] < qty:
raise CortexError(HAS_ONLY_ERROR, name, self.resources[name]['qty'], self.category)
self.resources[name]['qty'] -= qty
self.cursor.execute("UPDATE RESOURCE SET QTY=:qty WHERE GUID=:db_guid", {'qty':self.resources[name]['qty'], 'db_guid':self.resources[name]['db_guid']})
self.db.commit()
return self.output(name)
def clear(self, name):
"""Remove a name from the catalog entirely."""
if not name in self.resources:
raise CortexError(HAS_NONE_ERROR, name, self.category)
self.cursor.execute("DELETE FROM RESOURCE WHERE GUID=:db_guid", {'db_guid':self.resources[name]['db_guid']})
self.db.commit()
del self.resources[name]
return 'Cleared {0} from {1} list.'.format(name, self.category)
def output(self, name):
"""Return a formatted description of the resources held by a given name."""
return '*{0}*: {1}'.format(name, self.resources[name]['qty'])
def output_all(self):
"""Return a formatted summary of all resources."""
output = ''
prefix = ''
for name in list(self.resources):
output += prefix + self.output(name)
prefix = '\n'
return output
class GroupedNamedDice:
"""Holds named dice that are separated by groups, such as mental and physical stress (the dice names) assigned to characters (the dice groups)."""
def __init__(self, db, category, db_parent):
self.db = db
self.cursor = db.cursor()
self.groups = {}
self.category = category
self.db_parent = db_parent
self.cursor.execute("SELECT * FROM DICE_COLLECTION WHERE PARENT_GUID=:parent_guid AND CATEGORY=:category", {'parent_guid':self.db_parent.db_guid, 'category':self.category})
group_guids = {}
fetching = True
while fetching:
row = self.cursor.fetchone()
if row:
group_guids[row['GRP']] = row['GUID']
else:
fetching = False
for group in group_guids:
new_group = NamedDice(self.db, self.category, group, self.db_parent, db_guid=group_guids[group])
self.groups[group] = new_group
def is_empty(self):
"""Identifies whether we're holding any dice yet."""
return not self.groups
def remove_from_db(self):
"""Remove all of these dice from the database."""
for group in list(self.groups):
self.groups[group].remove_from_db()
self.groups = {}
def add(self, group, name, die):
"""Add dice with a given name to a given group."""
if not group in self.groups:
self.groups[group] = NamedDice(self.db, self.category, group, self.db_parent)
return self.groups[group].add(name, die)
def remove(self, group, name):
"""Remove dice with a given name from a given group."""
if not group in self.groups:
raise CortexError(HAS_NONE_ERROR, group, self.category + ' dice')
output = self.groups[group].remove(name)
if self.groups[group].is_empty():
self.groups[group].remove_from_db()
del self.groups[group]
return output
def clear(self, group):
"""Remove all dice from a given group."""
if not group in self.groups:
raise CortexError(HAS_NONE_ERROR, group, self.category + ' dice')
self.groups[group].remove_from_db()
del self.groups[group]
return 'Cleared all {0} for {1}.'.format(self.category, group)
def step_up(self, group, name, steps=1):
"""Step up the die with a given name, within a given group."""
if not group in self.groups:
raise CortexError(HAS_NONE_ERROR, group, self.category + ' dice')
return self.groups[group].step_up(name, steps)
def step_down(self, group, name, steps=1):
"""Step down the die with a given name, within a given group."""
if not group in self.groups:
raise CortexError(HAS_NONE_ERROR, group, self.category + ' dice')
output = self.groups[group].step_down(name, steps)
if self.groups[group].is_empty():
self.groups[group].remove_from_db()
del self.groups[group]
return output
def output(self, group):
"""Return a formatted list of all the dice within a given group."""
if self.groups[group].is_empty():
return '{0}: None'.format(group)
return '*{0}*: {1}'.format(group, self.groups[group].output_all(separator=', '))
def output_all(self):
"""Return a formatted summary of all dice under all groups."""
output = ''
prefix = ''
for group in list(self.groups):
output += prefix + self.output(group)
prefix = '\n'
return output
class CortexGame:
"""All information for a game, within a single server and channel."""
def __init__(self, db, server, channel):
self.db = db
self.cursor = db.cursor()
self.server = server
self.channel = channel
self.pinned_message = None
self.cursor.execute('SELECT * FROM GAME WHERE SERVER=:server AND CHANNEL=:channel', {"server":server, "channel":channel})
row = self.cursor.fetchone()
if not row:
self.db_guid = uuid.uuid1().hex
self.cursor.execute('INSERT INTO GAME (GUID, SERVER, CHANNEL, ACTIVITY) VALUES (?, ?, ?, ?)', (self.db_guid, server, channel, datetime.now(timezone.utc)))
self.db.commit()
else:
self.db_guid = row['GUID']
self.pinned_message = row['PIN']
self.new()
def new(self):
"""Set up new, empty traits for the game."""
self.complications = GroupedNamedDice(self.db, 'complication', self)
self.assets = GroupedNamedDice(self.db, 'asset', self)
self.distinctions = GroupedNamedDice(self.db, 'distinction', self)
self.pools = DicePools(self.db, self)
self.plot_points = Resources(self.db, 'plot points', self)
self.stress = GroupedNamedDice(self.db, 'stress', self)
self.xp = Resources(self.db, 'xp', self)