-
Notifications
You must be signed in to change notification settings - Fork 0
/
dice_distro.py
2203 lines (1824 loc) · 67.8 KB
/
dice_distro.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 __future__ import print_function
import argparse
import decimal
import functools
import importlib
import itertools
import json
import math
import operator
import os
import random
import sys
from collections import Counter
if (2, 0) <= sys.version_info < (3, 0):
zip = itertools.izip
def prod_values(xx):
return functools.reduce(operator.mul, xx, 1)
ITERABLE_TYPES = (list, tuple)
NUMERIC_TYPES = (int, float)
OPERATIONS_DICT = {
'id':lambda xx: xx,
'sum':lambda xx: (sum(xx),),
'min':lambda xx: (min(xx),),
'max':lambda xx: (max(xx),),
'sort':lambda xx: tuple(sorted(xx)),
'prod':lambda xx: (prod_values(xx),),
'bit-or':lambda xx: (functools.reduce(operator.or_, xx, 0),),
'bit-xor':lambda xx: (functools.reduce(operator.xor, xx),),
'bit-and':lambda xx: (functools.reduce(operator.and_, xx),),
'add': None, # This will get defined later if used
'scale': None, # This will get defined later if used
'exp': None, # This will get defined later if used
'set-to': None, # This will get defined later if used
'bound': None, # This will get defined later if used
'select': None, # This will get defined later if used
'reroll': None, # This will get defined later if used,
'slice-apply': None, # This will get defined later if used,
}
CUSTOM_OPERATIONS_DICT = dict()
BASIC_OPERATIONS = set(
key for key, value in OPERATIONS_DICT.items() if value is not None
)
ROUNDING_OPTIONS = {
'r-ceil': math.ceil,
'r-floor': math.floor,
'r-truncate': int,
'r-half-up': lambda xx: decimal.Decimal(xx).quantize(
decimal.Decimal('1'),
rounding = decimal.ROUND_HALF_UP,
),
'r-half-down': lambda xx: decimal.Decimal(xx).quantize(
decimal.Decimal('1'),
rounding = decimal.ROUND_HALF_DOWN,
),
}
# set of operations that support an if-block
IF_ABLE_OPERATIONS = set([
'add',
'scale',
'exp',
'set-to',
'bound',
'reroll',
])
ELSE_ABLE_OPERATIONS = set([
'add',
'scale',
'exp',
'set-to',
'bound',
])
BASIC_COMPARE_DICT = {
'ne':lambda aa, bb, cc=None: aa != bb,
'eq':lambda aa, bb, cc=None: aa == bb,
'gt':lambda aa, bb, cc=None: aa > bb,
'ge':lambda aa, bb, cc=None: aa >= bb,
'lt':lambda aa, bb, cc=None: aa < bb,
'le':lambda aa, bb, cc=None: aa <= bb,
}
LOGIC_START_KEYWORD = 'if'
LOGIC_ELSE_KEYWORD = 'else'
LOGIC_END_KEYWORD = 'then'
LOGIC_KEYWORDS = set([
LOGIC_START_KEYWORD,
LOGIC_ELSE_KEYWORD,
LOGIC_END_KEYWORD,
])
BOOLEAN_LOGIC_OPERATOR_ORDER = ['not', 'and', 'or']
BOOLEAN_LOGIC_OPERATORS = set(BOOLEAN_LOGIC_OPERATOR_ORDER)
COMPARE_KEYWORDS_SET = set.union(
set([
'mod',
]),
set(BASIC_COMPARE_DICT.keys()),
BOOLEAN_LOGIC_OPERATORS,
)
BRACKET_CHARS = ["[", "]"]
# Die defaults
DEFAULT_DIE_START = int(1)
DEFAULT_DIE_STEP = int(1)
DEFAULT_DIE_WEIGHT = int(1)
class CustomFormatter(argparse.HelpFormatter):
"""
Utilized code from:
- https://github.com/bewest/argparse/blob/master/argparse.py
class RawDescriptionHelpFormatter(HelpFormatter)
class ArgumentDefaultsHelpFormatter(HelpFormatter)
RawTextHelpFormatter._split_lines
- https://bitbucket.org
/ruamel
/std.argparse
/src
/cd5e8c944c5793fa9fa16c3af0080ea31f2c6710
/__init__.py?at=default&fileviewer=file-view-default
R| - Raw text, no indentation will be added
D| - Pad with white space
"""
def __init__(self, *args, **kw):
self._add_defaults = None
super(CustomFormatter, self).__init__(*args, **kw)
def _split_lines(self, text, width):
# this is the RawTextHelpFormatter._split_lines
if text.startswith('R|'):
return text[2:].splitlines()
elif text.startswith('D|'):
return [item.strip() for item in text[2:].splitlines()]
return argparse.HelpFormatter._split_lines(self, text, width)
def _fill_text(self, text, width, indent):
# this is the RawDescriptionHelpFormatter._fill_text
if text.startswith('R|'):
return text[2:]
if text.startswith('D|'):
text = text[2:]
return argparse.HelpFormatter._fill_text(self, text, width, indent)
def _get_help_string(self, action):
_help = action.help
if '%(default)' not in action.help:
if action.default is not argparse.SUPPRESS:
defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
_help += ' (default: %(default)s)'
return _help
def parse_number(compare_func, type_string, type=int):
if not issubclass(type, NUMERIC_TYPES):
raise Exception('Type passed must be either int or float')
if not hasattr(compare_func, '__call__'):
raise Exception('A function must be passed to parse_number.')
def parse_number_compare(value):
ivalue = type(value)
if not compare_func(ivalue):
raise argparse.ArgumentTypeError(
"{} is an invalid {} value of type {}".format(
value,
type_string,
str(type),
))
return ivalue
return parse_number_compare
parser = argparse.ArgumentParser(
formatter_class=CustomFormatter,
description="\n".join([
"This program is used to calculate the distributions of",
"dice rolling (using brute force enumeration) with operations",
"applied to results of the roll (via brute force calculations).",
]),
)
parser.add_argument(
"--show-args",
action='store_true',
help=" ".join([
"This is used for debuging purposes.",
"This will print out the parameters used to console,",
"before running a calculation",
]),
)
"""
========================================================================================
Single Die Options
========================================================================================
"""
single_type_group = parser.add_argument_group(
title='Single Die Type Options',
description='Use these flags when wanting to roll a specific die type.',
)
single_type_group.add_argument(
"--num-dice", "-n",
type=parse_number(lambda xx: xx > 0, 'positive'),
default=1,
help="Number of dice simulated",
)
single_type_group_side_option = single_type_group.add_mutually_exclusive_group()
single_type_group_side_option.add_argument(
"--die-sides", "-d",
type=parse_number(lambda xx: xx > 0, 'positive'),
help=" ".join([
"Number of sides the dice simulated should have.",
"The value given must be a positive integer.",
"The values on the die will start from '--die-start' and",
"fill up the sides of the die incrementing by '--die-step'.",
"This and '--die-values' are mutually exclusive options."
]),
)
single_type_group.add_argument(
"--die-start",
type=int,
default=DEFAULT_DIE_START,
help=" ".join([
"If using '--die-sides' this defines the lowest value of the die.",
"This option is ignored if '--die-sides' is not used.",
]),
)
single_type_group.add_argument(
"--die-step",
type=int,
default=DEFAULT_DIE_STEP,
help=" ".join([
"If using '--die-sides' this defines the increments",
"between values on the sides of the die.",
"This option is ignored if '--die-sides' is not used.",
]),
)
single_type_group_side_option.add_argument(
"--die-values",
type=int,
nargs="+",
default=[],
help=" ".join([
"The values the die should have.",
"Values are expected to be integers.",
"This and '--die-sides' are mutually exclusive options.",
]),
)
single_type_group.add_argument(
"--die-weights",
type=parse_number(lambda xx: xx > 0, 'positive', float),
nargs="+",
default=[],
help=" ".join([
"The weighting of the sides a die.",
"Values are expected to be integers or floats.",
]),
)
"""
========================================================================================
Multi Die Options
========================================================================================
"""
multi_type_group = parser.add_argument_group(
title='Multi Die Type Options',
description=" ".join([
'Use these flags when wanting to roll multiple types of dies at once.',
'When using flags from this group, the \'--multi-die-sides\' flag is required.',
]),
)
multi_type_group.add_argument(
"--multi-die-sides",
type=parse_number(lambda xx: xx > 0, 'positive'),
nargs="+",
help=" ".join([
"Number of sides the dice simulated should have.",
"This parameter is always used in when creating non-identical",
"dice to roll (multi-die-type) and thus is required."
"The value given must be a positive integer.",
"The values on the die will start from '--die-start'",
"and fill up the sides of the die incrementing by '--die-step'",
", unless you use '--multi-die-values' to specify each value on each die."
]),
)
multi_type_group.add_argument(
"--multi-die-start",
type=int,
nargs="+",
help=" ".join([
"If using '--die-sides' this defines the lowest value of the die.",
"This option is ignored if '--die-sides' is not used.",
"These values must be in parallel to '--multi-die-sides'",
]),
)
multi_type_group.add_argument(
"--multi-die-step",
type=int,
nargs="+",
help=" ".join([
"If using '--die-sides' this defines the increments between",
"values on the sides of the die.",
"This option is ignored if '--die-sides' is not used.",
"These values must be in parallel to '--multi-die-sides'",
]),
)
multi_type_group.add_argument(
"--multi-die-values",
type=int,
nargs="+",
default=[],
help=" ".join([
"The values the die should have.",
"Values are expected to be integers.",
"If using this option, '--multi-die-sides' must set.",
"The values are grabed in order.",
]),
)
multi_type_group.add_argument(
"--multi-die-weights",
type=parse_number(lambda xx: xx > 0, 'positive', float),
nargs="+",
default=[],
help=" ".join([
" The weighting of the sides a dice.",
"Values are expected to be integers or floats.",
"If using this option, '--multi-die-sides' must set.",
"The values are grabed in order.",
]),
)
"""
========================================================================================
Operation Options
========================================================================================
"""
op_group = parser.add_argument_group(
title='Operation Options',
description='Options how to deal with the result of rolls of the dice.',
)
op_group.add_argument(
"--apply",
type=str,
nargs="*",
default=['id'],
help="\n".join([
"D|"
# Intro block
"The operation that will be applied to the values rolled.",
"Operations can be chained, but it is up to the user to make",
"sure that the outputs of one are correct inputs for the other.",
# Explain if-block synatx
"Some operations can be applied conditionally, denoted by an",
"if-block between the operation string and its parameters.",
"Denote the end by using the keyword '{}'".format(LOGIC_END_KEYWORD),
"of the conditional statement",
"if more operation or parameters are needed.",
"Example Syntax:",
"'--apply op1 if cond1... then params1... then op2 if cond2... then params2...'",
"Note that if the last operation does not need parameters",
"but has an if-block, the final 'then' is not needed.",
# End of into block
# Define id operation
"---------------",
"The 'id' operation refers to the identity operation, which will",
"leave the input unchanged.",
# Define math operations operation
"---------------",
"The following operations:",
"'sum', 'min', 'max', 'set', 'prod', 'bit-or', 'bit-xor', 'bit-and'",
"apply their assosiated operation to all the dice.",
"An optional parameter can be given for a block-size, for block-wise application.",
"If the a block-size parameter is used, the results will be treated",
"as distinguishable dice.",
# Define sort operation
"---------------",
"The 'sort' operation sorts the result.",
"This has the effect of enumerating the results as",
"if the we treated the dice as indistiguishable.",
# Define add operation
"---------------",
"The 'add' operation will add a static value to all results",
"(you can specify the value per die).",
# Define bound operation
"---------------",
"The 'bound' operation will keep the values within specified upper and",
"lower bound (can be spcified per die).",
# Define reroll operation
"---------------",
"The 'reroll' will assume ordered dice rolls.",
"To be useful, 'reroll' should be given an if block",
"otherwise, the die is always rerolled and the final roll will just be used.",
# Define scale
"---------------",
"The 'scale' operation multiplies the value of the die by the parameter(s) given",
"The parameter(s) can be floating point values but the result(s) will be rounded.",
"The rounding option must be given before any of the numeric scale parameter(s).",
"The rounding options are:",
"'r-ceil', 'r-floor', 'r-truncate', 'r-half-up', 'r-half-down'",
# Define exp
"---------------",
"The 'exp' operation exponentiates the die value by the parameter(s).",
"A parameter 'as-base' can be passed before any of the numeric parameter(s).",
"This parameter will cause the parameter(s) passed to be used as the base and the",
"die value as the exponent.",
"The parameter(s) can be floating point values but the result(s) will be rounded.",
"The rounding option must be given before any of the numeric scale parameter(s).",
"The rounding options are:",
"'r-ceil', 'r-floor', 'r-truncate', 'r-half-up', 'r-half-down'",
# Define slice-apply operation
"---------------",
"The 'slice-apply' will take an block-size parameter to split the current",
"dice pool into blocks.",
"The immideate subsequent operation is applied to each block independently.",
"Operations applied after the immideate subsequent one will be applied to the",
"whole dice pool again (unless 'slice-apply' is used again).",
# Define select operation
"---------------",
"The 'select' operation requires at least one integer parameter.",
"This parameter is the index of the item in the sorted array.",
"Example-Select-1: '--apply select 0' is the same as min.",
"Example-Select-2: '--apply select 1' returns the second lowest value.",
"Example-Select-3: '--apply select -1' is the same as max.",
"Example-Select-4: '--apply select -2' returns the second highest value.",
]),
)
op_group.add_argument(
"--memorize-input",
action='store_true',
help=" ".join([
"An option for cashing results when applying the operation to a set of dice.",
"This will hash the results of a roll, and save the result.",
"This speeds up some calculations, but adds overhead since you",
"must calculate the hash of the input.",
"This flag is not useful if input doesn't repeat."
]),
)
op_group.add_argument(
"--skip-checks",
action='store_false',
dest="should_valdiate_input",
help=" ".join([
"This option will skip add a validation step to make sure the dice input",
"from one operation is approximate for the next.",
"This flag will speed up run time at the expense of more obscure errors.",
]),
)
op_group.add_argument(
"--custom",
type=str,
nargs="*",
default=[],
help=" ".join([
"These files will be imported by the program as python files.",
"Make sure that all file names are unique, as well as all",
"function names between files. Any function prefixed with '_'",
"will also not be included.",
"Any function accessable can be used as operations in",
"the '--apply' command string. Your functions should expect the",
"first parameter to be a tuple of ints (the dice rolls).",
"If you pass your operation parameters, they will be passed as",
"positional args after the first.",
"The function must either return an ints or an ordered",
"list/tuple of ints."
]),
)
"""
========================================================================================
Bar Options
========================================================================================
"""
bar_group = parser.add_argument_group(
title='Bar Options',
description='Options related to the bar rendering',
)
bar_group.add_argument(
"--bar-size",
type=parse_number(lambda xx: xx >= 0, 'non-negative', float),
default=2,
help=" ".join([
"The approximate number of '--bar-char'(s) that count as 1 percent.",
"If '--bar-size' is set to zero, then no bars will be displayed.",
]),
)
bar_group.add_argument(
"--bar-char",
type=str,
default="=",
help=" ".join([
"The fill string used for the bar charts.",
"One percent is represented as this string repeated '--bar-size' times.",
]),
)
bar_group.add_argument(
"--bar-prefix",
type=str,
default="|",
help=" ".join([
"A prefix string used before the bar chart but after the display of percentage.",
"Will not be displayed if '--bar-size' is set to zero.",
]),
)
"""
========================================================================================
Display Output Options
========================================================================================
"""
display_output_group = parser.add_argument_group(
title='Display Output Options',
description='Options related to displaying calculated information',
)
display_output_group.add_argument(
"--sort",
type=str,
choices=["key", "value"],
default='key',
help=" ".join([
"This defines how the output is sorted.",
"Key refers to the die results.",
"Value refers to the counts or the probability of the results.",
]),
)
display_output_group.add_argument(
"--no-output",
action='store_false',
dest='display_output',
default=True,
help=" ".join([
"If this flag is set, there will be no output displayed."
]),
)
display_format_exclusive_options = display_output_group.add_mutually_exclusive_group()
display_format_exclusive_options.add_argument(
"--result-decimal-place", "-rdp",
type=parse_number(lambda xx: xx > 0, 'positive'),
default=2,
help=" ".join([
"The number of digits that will be displayed after the decimal place.",
"Can be used when displaying percentages or floating point counts",
"(which only happen when the die weights are floating point values).",
]),
)
display_format_exclusive_options.add_argument(
"--show-counts",
action="store_true",
help=" ".join([
"This flag will cause the counts to be displayed instead of the percentage.",
]),
)
display_output_group.add_argument(
"--average",
action='store_true',
help=" ".join([
"Calculated weighted average of dice outcome.",
"If the outcomes are multi-valued, the values are added like vectors.",
]),
)
CUMULATIVE_CHOICES = ["normal", "reversed"]
display_output_group.add_argument(
"--cumulative",
const=CUMULATIVE_CHOICES[0],
choices=CUMULATIVE_CHOICES,
nargs='?',
default=None,
help=" ".join([
"Display cumulative distrobution.",
"Only available with data outcomes that are singletons.",
"This the outcome must be well ordered.",
"If flag is passed without a choice, then 'normal' is used."
]),
)
"""
========================================================================================
Simulate Options
========================================================================================
"""
simulate_group = parser.add_argument_group(
title='Simulate Options',
description=' '.join([
'Options related to simulating the dice rolls rather than enumerating all the outcomes.',
'Useful if the compute time of calculating all the outcomes takes too long.',
'This will only provide an approximation of the results.',
]),
)
simulate_group.add_argument(
'--simulate',
dest='simulate_num_iterations',
type=parse_number(lambda xx: xx > 0, 'positive'),
default=None,
help=" ".join([
"The number of simulated dice rols that will occur.",
"If this option is not provided, then enumerating all outcomes will take place.",
]),
)
"""
========================================================================================
File Save/Load Options
========================================================================================
"""
file_save_load_options = parser.add_argument_group(
title='Save/Load Options',
description=' '.join([
'Options related to saving data and loading data'
]),
)
file_save_load_options.add_argument(
'--load',
dest='load_file_paths',
type=str,
nargs="*",
default=None,
help=" ".join([
"The file path of where you want the data loaded from.",
"NOTE: If this parameter is used, all dice generation parameters will be ignored.",
]),
)
file_save_load_options.add_argument(
'--save',
dest='save_file_path',
type=str,
default=None,
help=" ".join([
"The file path of where you want the data saved.",
]),
)
def always_true(*args, **kwargs):
return True
def apply_not(func):
def not_func(*args, **kwargs):
return not func(*args, **kwargs)
return not_func
def apply_and(*funcs):
def and_func(*args, **kwargs):
return all(func(*args, **kwargs) for func in funcs)
return and_func
def apply_or(*funcs):
def or_func(*args, **kwargs):
return any(func(*args, **kwargs) for func in funcs)
return or_func
def docstring_format(*args, **kwargs):
def decorator(func):
func.__doc__ = func.__doc__.format(*args, **kwargs)
return func
return decorator
def indent_text(text,indent=4*" "):
if not text:
return ''
return "\n".join(indent + line for line in text.split("\n"))
def dice_input_checker(func):
func_str_info = "\n".join([
"Func Name: {}".format(func.__name__),
"Doc String: {}".format(func.__doc__)
])
def check_is_tuple(xx, kind):
if not isinstance(xx, tuple):
raise Exception(
"\n".join([
func_str_info,
'{} of operation is not an instance of `list` or `tuple`. Given: {}'.format(
kind.title(),
str(xx),
),
])
)
def check_all_int(xx, kind):
if not all(isinstance(item, int) for item in xx):
raise Exception(
"\n".join([
func_str_info,
'Entries in the {} list/tuple are not integers. Given: {}'.format(
kind.lower(),
str(xx),
),
])
)
@functools.wraps(func)
def wrapper(xx):
check_is_tuple(xx, 'input')
check_all_int(xx, 'input')
result = func(xx)
check_is_tuple(result, 'output')
check_all_int(result, 'output')
return result
return wrapper
def memorize(func):
cashe = dict()
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = (tuple(args), frozenset(kwargs.items()))
if key in cashe: return cashe[key]
result = func(*args, **kwargs)
cashe[key] = result
return result
return wrapper
def find_max_digits(iterable):
if not all(isinstance(xx, NUMERIC_TYPES) for xx in iterable):
raise Exception('All items in the iterable must be ints or floats.')
return max(len(str(xx)) for xx in iterable)
def intersperse(lst, item):
result = [item] * (len(lst) * 2 - 1)
result[0::2] = lst
return result
def simple_clean_params(param_list):
"""
This function expects the parameter list
It will split up the brackets so that each bracket is it's own entry
as well as remove any extra white space
"""
temp_list = list(param_list)
for bracket in BRACKET_CHARS:
_temp_list = []
for item1 in temp_list:
if bracket in item1:
item2 = item1.split(bracket)
_temp_list.extend(
item3
for item3 in intersperse(item2, bracket) if item3
)
elif item1:
_temp_list.append(item1)
temp_list = _temp_list
return temp_list
def custom_func_wrapper(
custom_func,
cur_params=tuple(),
should_validate=True,
):
@functools.wraps(custom_func)
def custom_operation(xx):
result = custom_func(xx, *cur_params)
if not should_validate:
# short ciruit the checks
pass
elif isinstance(result, int):
result = (result,)
elif isinstance(result, list):
result = tuple(result)
elif not isinstance(result, tuple):
raise Exception("Custom function has returned a value that is not supported.")
if should_validate and any(not isinstance(item, int) for item in result):
raise Exception("Values passed are not all ints.")
return result
return custom_operation
def composed_func_wrapper(
first_func,
second_func,
):
@docstring_format(
indent_text(first_func.__doc__),
indent_text(second_func.__doc__),
)
def composite_operation(xx):
"""
Composite Operation
--------------------
First Operation Doc:
{}
--------------------
Second Operation Doc:
{}
--------------------
"""
return second_func(first_func(xx))
return composite_operation
def load_custom_files(file_paths):
custom_dirs = set()
file_names = set()
for path in file_paths:
abs_path = os.path.abspath(path)
file_dir = os.path.dirname(abs_path)
prefix_path, _ = os.path.splitext(abs_path)
basename = os.path.basename(prefix_path)
if basename in file_names:
raise Exception("File name is not unique")
if not os.path.isfile(abs_path):
raise Exception("File path give is not a valid file: {}".format(path))
file_names.add(basename)
custom_dirs.add(file_dir)
for dir_path in custom_dirs:
sys.path.append(dir_path)
for module_name in file_names:
the_module = importlib.import_module(module_name)
for attr_name in dir(the_module):
if attr_name.startswith("_"): continue
attr_object = getattr(the_module, attr_name, None)
if hasattr(attr_object, "__call__"):
if attr_name in CUSTOM_OPERATIONS_DICT:
raise Exception('operation_name collision, please make sure you ')
CUSTOM_OPERATIONS_DICT[attr_name] = attr_object
def get_single_dice(args):
"""
Create a tuple of 'args.num_dice' many dice
where each die is the same.
"""
if all([
isinstance(args.die_sides, int) and args.die_sides > 0,
isinstance(args.die_values, ITERABLE_TYPES) and args.die_values,
]):
raise Exception("Both die sides are given and die values are given. Only pass one")
elif isinstance(args.die_sides, int) and args.die_sides > 0:
face_values = range(
args.die_start,
args.die_start + args.die_step * args.die_sides,
args.die_step,
)
elif args.die_values:
face_values = args.die_values
else:
raise Exception('Must pass in one of \'--die\' or \'--die-values\'')
if isinstance(args.die_weights, ITERABLE_TYPES) and args.die_weights:
if len(face_values) != len(args.die_weights):
raise Exception(
"The number of die counts must the same as the number of face values present on the die."
)
weight_values = args.die_weights
else:
weight_values = [DEFAULT_DIE_WEIGHT for _ in face_values]
return tuple(tuple(zip(face_values, weight_values)) for _ in range(args.num_dice))
def get_multi_dice(args):
"""
Create a tuple of dice were each die may not have the same number
of sides as any other die
"""
dice = []
if not isinstance(args.multi_die_sides, ITERABLE_TYPES) or not args.multi_die_sides:
raise Exception(
"The parameter '--multi-die-sides' is a required parameter for multi-die-type rolls"
)
if (
isinstance(args.multi_die_weights, ITERABLE_TYPES) and
args.multi_die_weights and
len(args.multi_die_weights) != sum(args.multi_die_sides)
):
raise Exception(
"The number of weights given should be equal to the facees on all dies that will be rolled."
)
if isinstance(args.multi_die_values, ITERABLE_TYPES) and args.multi_die_values:
"""
Process args to return dice were each die has unique specified values
Values are specified from 'args.multi_die_values' and values are grouped
into sections specified by args.multi_die_sides.
"""
if isinstance(args.multi_die_weights, ITERABLE_TYPES) and args.multi_die_weights:
iterator = zip(args.multi_die_values, args.multi_die_weights)
else:
iterator = zip(args.multi_die_values, itertools.repeat(DEFAULT_DIE_WEIGHT))
die = []
for die_face in iterator:
die.append(die_face)
if len(die) == args.multi_die_sides[len(dice)]:
dice.append(tuple(die))
die = []
if len(dice) != len(args.multi_die_sides):
raise Exception("Not enough die values were given")
if sum(len(item) for item in dice) != len(args.multi_die_values):
raise Exception("Not all die values were used")
else:
"""
Process args to return dice you specify a:
- start value
- increment vlaue
- number of steps to take (number of sides on the die)
"""
if isinstance(args.multi_die_start, ITERABLE_TYPES) and args.multi_die_start:
if len(args.multi_die_start) != len(args.multi_die_sides):
raise Exception("Multi die starts must have parallel values to multi die sides")
start_values = args.multi_die_start
else:
start_values = tuple(DEFAULT_DIE_START for _ in args.multi_die_sides)
if isinstance(args.multi_die_step, ITERABLE_TYPES) and args.multi_die_step:
if len(args.multi_die_step) != len(args.multi_die_step):
raise Exception("Multi die steps must have parallel values to multi die sides")
step_values = args.multi_die_step
else:
step_values = tuple(DEFAULT_DIE_STEP for _ in args.multi_die_sides)
if isinstance(args.multi_die_weights, ITERABLE_TYPES) and args.multi_die_weights:
weight_value_sets = []
temp_list = list(args.multi_die_weights)
for nn in args.multi_die_sides: