/
initTracker.py
1314 lines (1108 loc) · 55.4 KB
/
initTracker.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
import collections
import functools
import logging
import random
import traceback
import discord
from d20 import roll
from discord.ext import commands
from discord.ext.commands import NoPrivateMessage
from cogs5e.funcs import attackutils, checkutils, targetutils
from gamedata.lookuputils import select_monster_full, select_spell_full
from aliasing import helpers
from cogs5e.models.character import Character
from cogs5e.models.embeds import EmbedWithAuthor, EmbedWithCharacter
from cogs5e.models.errors import InvalidArgument, SelectionException
from cogs5e.models.initiative import Combat, Combatant, CombatantGroup, Effect, MonsterCombatant, PlayerCombatant
from cogs5e.models.sheet.attack import Attack
from cogs5e.models.sheet.base import Skill
from cogs5e.models.sheet.resistance import Resistances
from cogsmisc.stats import Stats
from utils.argparser import argparse, argsplit
from utils.functions import confirm, search_and_select, try_delete
log = logging.getLogger(__name__)
DM_ROLES = {"dm", "gm", "dungeon master", "game master"}
class InitTracker(commands.Cog):
"""
Initiative tracking commands. Use !help init for more details.
To use, first start combat in a channel by saying "!init begin".
Then, each combatant should add themselves to the combat with "!init add <MOD> <NAME>".
To hide a combatant's HP, add them with "!init add <MOD> <NAME> -h".
Once every combatant is added, each combatant should set their max hp with "!init hp <NAME> max <MAXHP>".
Then, you can proceed through combat with "!init next".
Once combat ends, end combat with "!init end".
For more help, the !help command shows applicable arguments for each command.
"""
def __init__(self, bot):
self.bot = bot
@commands.group(aliases=['i'], invoke_without_command=True)
async def init(self, ctx):
"""Commands to help track initiative."""
await ctx.send(f"Incorrect usage. Use {ctx.prefix}help init for help.")
async def cog_check(self, ctx):
if ctx.guild is None:
raise NoPrivateMessage()
return True
async def cog_before_invoke(self, ctx):
await try_delete(ctx.message)
@init.command()
async def begin(self, ctx, *args):
"""Begins combat in the channel the command is invoked.
Usage: !init begin <ARGS (opt)>
__Valid Arguments__
dyn - Dynamic initiative; Rerolls all initiatves at the start of a round.
turnnotif - Notifies the controller of the next combatant in initiative.
-name <name> - Sets a name for the combat instance."""
await Combat.ensure_unique_chan(ctx)
options = {}
args = argparse(args)
if args.last('dyn', False, bool): # rerolls all inits at the start of each round
options['dynamic'] = True
if 'name' in args:
options['name'] = args.last('name')
if args.last('turnnotif', False, bool):
options['turnnotif'] = True
temp_summary_msg = await ctx.send("```Awaiting combatants...```")
Combat.message_cache[temp_summary_msg.id] = temp_summary_msg # add to cache
combat = Combat.new(str(ctx.channel.id), temp_summary_msg.id, str(ctx.author.id), options, ctx)
await combat.final()
try:
await temp_summary_msg.pin()
except:
pass
await ctx.send(
f"Everyone roll for initiative!\n"
f"If you have a character set up with SheetManager: `{ctx.prefix}init join`\n"
f"If it's a 5e monster: `{ctx.prefix}init madd <monster name>`\n"
f"Otherwise: `{ctx.prefix}init add <modifier> <name>`")
@init.command()
async def add(self, ctx, modifier: int, name: str, *args):
"""Adds a generic combatant to the initiative order.
Generic combatants have a 10 in every stat and +0 to every modifier.
If a character is set up with the SheetManager module, you can use !init join instead.
If you are adding monsters to combat, you can use !init madd instead.
__Valid Arguments__
-h - Hides HP, AC, resistances, and attack list.
-p - Places combatant at the given modifier, instead of rolling
-controller <controller> - Pings a different person on turn.
-group <group> - Adds the combatant to a group.
-hp <hp> - Sets starting HP. Default: None.
-thp <thp> - Sets starting THP. Default: 0.
-ac <ac> - Sets the combatant' AC. Default: None.
-resist <damage type> - Gives the combatant resistance to the given damage type.
-immune <damage type> - Gives the combatant immunity to the given damage type.
-vuln <damage type> - Gives the combatant vulnerability to the given damage type.
adv/dis - Rolls the initiative check with advantage/disadvantage.
"""
private = False
place = None
controller = str(ctx.author.id)
group = None
hp = None
ac = None
resists = {}
args = argparse(args)
adv = args.adv(boolwise=True)
thp = args.last('thp', type_=int)
if args.last('h', type_=bool):
private = True
if 'p' in args:
try:
place_arg = args.last('p')
if place_arg is True:
place = modifier
else:
place = int(place_arg)
except (ValueError, TypeError):
place = modifier
if args.last('controller'):
controller_name = args.last('controller')
member = await commands.MemberConverter().convert(ctx, controller_name)
controller = str(member.id) if member is not None else controller
if args.last('group'):
group = args.last('group')
if args.last('hp'):
hp = args.last('hp', type_=int)
if hp < 1:
return await ctx.send("You must pass in a positive, nonzero HP with the -hp tag.")
if args.last('ac'):
ac = args.last('ac', type_=int)
for k in ('resist', 'immune', 'vuln'):
resists[k] = args.get(k)
combat = await Combat.from_ctx(ctx)
if combat.get_combatant(name) is not None:
await ctx.send("Combatant already exists.")
return
if not place:
init_skill = Skill(modifier, adv=adv)
init_roll = roll(init_skill.d20())
init = init_roll.total
init_roll_skeleton = init_roll.result
else:
init_skill = Skill(0, adv=adv)
init = place
init_roll_skeleton = str(init)
me = Combatant.new(name, controller, init, init_skill, hp, ac, private, Resistances.from_dict(resists), ctx,
combat)
# -thp (#1142)
if thp and thp > 0:
me.temp_hp = thp
if group is None:
combat.add_combatant(me)
await ctx.send(f"{name} was added to combat with initiative {init_roll_skeleton}.")
else:
grp = combat.get_group(group, create=init)
grp.add_combatant(me)
await ctx.send(f"{name} was added to combat with initiative {grp.init} as part of group {grp.name}.")
await combat.final()
@init.command()
async def madd(self, ctx, monster_name: str, *args):
"""Adds a monster to combat.
__Valid Arguments__
adv/dis - Give advantage or disadvantage to the initiative roll.
-b <condition bonus> - Adds a bonus to the combatant's initiative roll.
-n <number> - Adds more than one of that monster.
-p <value> - Places combatant at the given value, instead of rolling.
-name <name> - Sets the combatant's name. Use "#" for auto-numbering, e.g. "Orc#"
-h - Hides HP, AC, Resists, etc. Default: True.
-group <group> - Adds the combatant to a group.
-rollhp - Rolls the monsters HP, instead of using the default value.
-hp <hp> - Sets starting HP.
-thp <thp> - Sets starting THP.
-ac <ac> - Sets the combatant's starting AC."""
monster = await select_monster_full(ctx, monster_name, pm=True)
args = argparse(args)
private = not args.last('h', type_=bool)
group = args.last('group')
adv = args.adv(boolwise=True)
b = args.join('b', '+')
p = args.last('p', type_=int)
rollhp = args.last('rollhp', False, bool)
hp = args.last('hp', type_=int)
thp = args.last('thp', type_=int)
ac = args.last('ac', type_=int)
n = args.last('n', 1, int)
name_template = args.last('name', monster.name[:2].upper() + '#')
init_skill = monster.skills.initiative
combat = await Combat.from_ctx(ctx)
out = ''
to_pm = ''
recursion = 25 if n > 25 else 1 if n < 1 else n
name_num = 1
for i in range(recursion):
name = name_template.replace('#', str(name_num))
raw_name = name_template
to_continue = False
while combat.get_combatant(name) and name_num < 100: # keep increasing to avoid duplicates
if '#' in raw_name:
name_num += 1
name = raw_name.replace('#', str(name_num))
else:
out += "Combatant already exists.\n"
to_continue = True
break
if to_continue:
continue
try:
check_roll = None # to make things happy
if p is None:
if b:
check_roll = roll(f'{init_skill.d20(base_adv=adv)}+{b}')
else:
check_roll = roll(init_skill.d20(base_adv=adv))
init = check_roll.total
else:
init = int(p)
controller = str(ctx.author.id)
# -hp
rolled_hp = None
if rollhp:
rolled_hp = roll(monster.hitdice)
to_pm += f"{name} began with {rolled_hp.result} HP.\n"
rolled_hp = max(rolled_hp.total, 1)
me = MonsterCombatant.from_monster(monster, ctx, combat, name, controller, init, private,
hp=hp or rolled_hp, ac=ac)
# -thp (#1142)
if thp and thp > 0:
me.temp_hp = thp
if group is None:
combat.add_combatant(me)
out += f"{name} was added to combat with initiative {check_roll.result if p is None else p}.\n"
else:
grp = combat.get_group(group, create=init)
grp.add_combatant(me)
out += f"{name} was added to combat with initiative {grp.init} as part of group {grp.name}.\n"
except Exception as e:
log.warning('\n'.join(traceback.format_exception(type(e), e, e.__traceback__)))
out += "Error adding combatant: {}\n".format(e)
await combat.final()
await ctx.send(out)
if to_pm:
await ctx.author.send(to_pm)
@init.command(name='join', aliases=['cadd', 'dcadd'])
async def join(self, ctx, *, args: str = ''):
"""
Adds the current active character to combat. A character must be loaded through the SheetManager module first.
__Valid Arguments__
adv/dis - Give advantage or disadvantage to the initiative roll.
-b <condition bonus> - Adds a bonus to the combatants' Initiative roll.
-phrase <phrase> - Adds flavor text.
-thumb <thumbnail URL> - Adds flavor image.
-p <value> - Places combatant at the given value, instead of rolling.
-h - Hides HP, AC, Resists, etc.
-group <group> - Adds the combatant to a group.
[user snippet]
"""
char: Character = await Character.from_ctx(ctx)
args = await helpers.parse_snippets(args, ctx)
args = await helpers.parse_with_character(ctx, char, args)
args = argparse(args)
embed = EmbedWithCharacter(char, False)
p = args.last('p', type_=int)
group = args.last('group')
if p is None:
args.ignore('rr')
args.ignore('dc')
checkutils.update_csetting_args(char, args, char.skills.initiative)
totals = checkutils.run_check('initiative', char, args, embed)
init = totals[-1]
else:
init = p
embed.title = "{} already rolled initiative!".format(char.name)
embed.description = "Placed at initiative `{}`.".format(init)
controller = str(ctx.author.id)
private = args.last('h', type_=bool)
combat = await Combat.from_ctx(ctx)
if combat.get_combatant(char.name) is not None:
await ctx.send("Combatant already exists.")
return
me = await PlayerCombatant.from_character(char, ctx, combat, controller, init, private)
if group is None:
combat.add_combatant(me)
embed.set_footer(text="Added to combat!")
else:
grp = combat.get_group(group, create=init)
grp.add_combatant(me)
embed.set_footer(text=f"Joined group {grp.name}!")
await combat.final()
await ctx.send(embed=embed)
@init.command(name="next", aliases=['n'])
async def nextInit(self, ctx):
"""Moves to the next turn in initiative order.
It must be your turn or you must be the DM (the person who started combat) to use this command."""
combat = await Combat.from_ctx(ctx)
if len(combat.get_combatants()) == 0:
await ctx.send("There are no combatants.")
return
allowed_to_pass = (combat.index is None) \
or (str(ctx.author.id) in (combat.current_combatant.controller, combat.dm)) \
or DM_ROLES.intersection({r.name.lower() for r in ctx.author.roles})
if not allowed_to_pass:
await ctx.send("It is not your turn.")
return
toRemove = []
if combat.current_combatant is not None:
if isinstance(combat.current_combatant, CombatantGroup):
thisTurn = combat.current_combatant.get_combatants()
else:
thisTurn = [combat.current_combatant]
for co in thisTurn:
if isinstance(co, MonsterCombatant) and co.hp <= 0:
toRemove.append(co)
advanced_round, messages = combat.advance_turn()
out = messages
await Stats.increase_stat(ctx, "turns_init_tracked_life")
if advanced_round:
await Stats.increase_stat(ctx, "rounds_init_tracked_life")
out.append(combat.get_turn_str())
for co in toRemove:
combat.remove_combatant(co)
out.append("{} automatically removed from combat.\n".format(co.name))
await ctx.send("\n".join(out))
await combat.final()
@init.command(name="prev", aliases=['previous', 'rewind'])
async def prevInit(self, ctx):
"""Moves to the previous turn in initiative order."""
combat = await Combat.from_ctx(ctx)
if len(combat.get_combatants()) == 0:
await ctx.send("There are no combatants.")
return
combat.rewind_turn()
await ctx.send(combat.get_turn_str())
await combat.final()
@init.command(name="move", aliases=['goto'])
async def moveInit(self, ctx, target=None):
"""Moves to a certain initiative.
`target` can be either a number, to go to that initiative, or a name.
If not supplied, goes to the first combatant that the user controls."""
combat = await Combat.from_ctx(ctx)
if len(combat.get_combatants()) == 0:
await ctx.send("There are no combatants.")
return
if target is None:
combatant = next((c for c in combat.get_combatants() if c.controller == str(ctx.author.id)), None)
if combatant is None:
return await ctx.send("You do not control any combatants.")
combat.goto_turn(combatant, True)
else:
try:
target = int(target)
combat.goto_turn(target)
except ValueError:
combatant = await combat.select_combatant(target)
combat.goto_turn(combatant, True)
await ctx.send(combat.get_turn_str())
await combat.final()
@init.command(name="skipround", aliases=['round', 'skiprounds'])
async def skipround(self, ctx, numrounds: int = 1):
"""Skips one or more rounds of initiative."""
combat = await Combat.from_ctx(ctx)
if len(combat.get_combatants()) == 0:
return await ctx.send("There are no combatants.")
if combat.index is None:
return await ctx.send(f"Please start combat with `{ctx.prefix}init next` first.")
toRemove = []
for co in combat.get_combatants():
if isinstance(co, MonsterCombatant) and co.hp <= 0 and co is not combat.current_combatant:
toRemove.append(co)
messages = combat.skip_rounds(numrounds)
out = messages
out.append(combat.get_turn_str())
for co in toRemove:
combat.remove_combatant(co)
out.append("{} automatically removed from combat.".format(co.name))
await ctx.send("\n".join(out))
await combat.final()
@init.command(name="reroll", aliases=['shuffle'])
async def reroll(self, ctx, *args):
"""
Rerolls initiative for all combatants, and starts a new round of combat.
__Valid Arguments__
-restart - Resets the round counter (effectively restarting initiative).
"""
combat = await Combat.from_ctx(ctx)
a = argparse(args)
new_order = combat.reroll_dynamic()
await ctx.send(f"Rerolled initiative! New order:\n{new_order}")
# -restart (#1053)
if a.last('restart'):
combat.round_num = 0
# repost summary message
old_summary = await combat.get_summary_msg()
new_summary = await ctx.send(combat.get_summary())
Combat.message_cache[new_summary.id] = new_summary # add to cache
combat.summary = new_summary.id
try:
await new_summary.pin()
await old_summary.unpin()
except:
pass
await combat.final()
@init.command(name="meta", aliases=['metaset'])
async def metasetting(self, ctx, *settings):
"""Changes the settings of the active combat.
__Valid Settings__
dyn - Dynamic initiative; Rerolls all initiatves at the start of a round.
turnnotif - Notifies the controller of the next combatant in initiative.
-name <name> - Sets a name for the combat instance"""
args = argparse(settings)
combat = await Combat.from_ctx(ctx)
options = combat.options
out = ""
if args.last('dyn', False, bool): # rerolls all inits at the start of each round
options['dynamic'] = not options.get('dynamic')
out += f"Dynamic initiative turned {'on' if options['dynamic'] else 'off'}.\n"
if args.last('name'):
options['name'] = args.last('name')
out += f"Name set to {options['name']}.\n"
if args.last('turnnotif', False, bool):
options['turnnotif'] = not options.get('turnnotif')
out += f"Turn notification turned {'on' if options['turnnotif'] else 'off'}.\n"
combat.options = options
await combat.commit()
await ctx.send(out)
@init.command(name="list", aliases=['summary'])
async def listInits(self, ctx, *args):
"""Lists the combatants.
__Valid Arguments__
private - Sends the list in a private message."""
combat = await Combat.from_ctx(ctx)
private = 'private' in args
destination = ctx if not private else ctx.author
if private and str(ctx.author.id) == combat.dm:
out = combat.get_summary(True)
else:
out = combat.get_summary()
await destination.send(out)
@init.command()
async def note(self, ctx, name: str, *, note: str = ''):
"""Attaches a note to a combatant."""
combat = await Combat.from_ctx(ctx)
combatant = await combat.select_combatant(name)
if combatant is None:
return await ctx.send("Combatant not found.")
combatant.notes = note
if note == '':
await ctx.send("Removed note.")
else:
await ctx.send("Added note.")
await combat.final()
@init.command(aliases=['opts'])
async def opt(self, ctx, name: str, *args):
"""Edits the options of a combatant.
__Valid Arguments__
-h - Hides HP, AC, Resists, etc.
-p <value> - Changes the combatants' placement in the Initiative. Adds if starts with +/- or sets otherwise.
-name <name> - Changes the combatants' name.
-controller <controller> - Pings a different person on turn.
-ac <ac> - Modifies combatants' AC. Adds if starts with +/- or sets otherwise.
-resist <damage type> - Gives the combatant resistance to the given damage type.
-immune <damage type> - Gives the combatant immunity to the given damage type.
-vuln <damage type> - Gives the combatant vulnerability to the given damage type.
-neutral <damage type> - Removes the combatants' immunity, resistance, or vulnerability to the given damage type.
-group <group> - Adds the combatant to a group. To remove them from group, use -group None.
-max <maxhp> - Modifies the combatants' Max HP. Adds if starts with +/- or sets otherwise.
-hp <hp> - Modifies current HP. Adds if starts with +/- or sets otherwise."""
combat = await Combat.from_ctx(ctx)
comb = await combat.select_combatant(name, select_group=True)
if comb is None:
await ctx.send("Combatant not found.")
return
args = argparse(args)
options = {}
target_is_group = isinstance(comb, CombatantGroup)
run_once = set()
def option(opt_name=None, pass_group=False, **kwargs):
"""
Wrapper to register an option.
:param str opt_name: The string to register the function under. Defaults to function name.
:param bool pass_group: Whether to pass a group as the first argument to the function or a combatant.
:param kwargs: kwargs that will always be passed to the function.
"""
def wrapper(func):
func_name = opt_name or func.__name__
if pass_group and target_is_group:
old_func = func
async def func(_, *a, **k):
if func_name in run_once:
return
run_once.add(func_name)
return await old_func(comb, *a, **k) # pop the combatant argument and sub in group
func = options[func_name] = functools.partial(func, **kwargs)
return func
return wrapper
def mod_or_set(opt_name, old_value):
new_value = args.last(opt_name, type_=int)
if args.last(opt_name).startswith(('-', '+')):
new_value = (old_value or 0) + new_value
return new_value, old_value
@option()
async def h(combatant):
combatant.is_private = not combatant.is_private
return f"\u2705 {combatant.name} {'hidden' if combatant.is_private else 'unhidden'}."
@option()
async def controller(combatant):
controller_name = args.last('controller')
member = await commands.MemberConverter().convert(ctx, controller_name)
if member is None:
return "\u274c New controller not found."
combatant.controller = str(member.id)
return f"\u2705 {combatant.name}'s controller set to {combatant.controller_mention()}."
@option()
async def ac(combatant):
try:
new_ac, old_ac = mod_or_set('ac', combatant.ac)
combatant.ac = new_ac
return f"\u2705 {combatant.name}'s AC set to {combatant.ac} (was {old_ac})."
except InvalidArgument as e:
return f"\u274c {str(e)}"
@option(pass_group=True)
async def p(combatant):
if combatant is combat.current_combatant:
return "\u274c You cannot change a combatant's initiative on their own turn."
try:
new_init, old_init = mod_or_set('p', combatant.init)
combatant.init = new_init
combat.sort_combatants()
return f"\u2705 {combatant.name}'s initiative set to {combatant.init} (was {old_init})."
except InvalidArgument as e:
return f"\u274c {str(e)}"
@option()
async def group(combatant):
current = combat.current_combatant
was_current = combatant is current or \
(isinstance(current, CombatantGroup) and combatant in current and len(current) == 1)
group_name = args.last('group')
combat.remove_combatant(combatant, ignore_remove_hook=True)
if group_name.lower() == 'none':
combat.add_combatant(combatant)
if was_current:
combat.goto_turn(combatant, True)
return f"\u2705 {combatant.name} removed from all groups."
else:
c_group = combat.get_group(group_name, create=combatant.init)
c_group.add_combatant(combatant)
if was_current:
combat.goto_turn(combatant, True)
return f"\u2705 {combatant.name} added to group {c_group.name}."
@option(pass_group=True)
async def name(combatant):
old_name = combatant.name
new_name = args.last('name')
if combat.get_combatant(new_name, True) is not None:
return f"\u274c There is already another combatant with the name {new_name}."
elif new_name:
combatant.name = new_name
return f"\u2705 {old_name}'s name set to {new_name}."
else:
return "\u274c You must pass in a name with the -name tag."
@option("max")
async def max_hp(combatant):
new_max, old_max = mod_or_set('max', combatant.max_hp)
if new_max < 1:
return "\u274c Max HP must be at least 1."
else:
combatant.max_hp = new_max
return f"\u2705 {combatant.name}'s HP max set to {new_max} (was {old_max})."
@option()
async def hp(combatant):
new_hp, old_hp = mod_or_set('hp', combatant.hp)
combatant.set_hp(new_hp)
return f"\u2705 {combatant.name}'s HP set to {new_hp} (was {old_hp})."
@option("resist", resist_type="resist")
@option("immune", resist_type="immune")
@option("vuln", resist_type="vuln")
@option("neutral", resist_type="neutral")
async def resist(combatant, resist_type):
result = []
for damage_type in args.get(resist_type):
damage_type = damage_type.lower()
combatant.set_resist(damage_type, resist_type)
result.append(damage_type)
return f"\u2705 Updated {combatant.name}'s {resist_type}s: {', '.join(result)}"
# run options
if target_is_group:
targets = comb.get_combatants().copy()
else:
targets = [comb]
out = collections.defaultdict(lambda: [])
for arg_name, opt_func in options.items():
if arg_name in args:
for target in targets:
response = await opt_func(target)
if response:
if target.is_private:
destination = ctx.guild.get_member(int(comb.controller)) or ctx.channel
else:
destination = ctx.channel
out[destination].append(response)
if out:
for destination, messages in out.items():
await destination.send('\n'.join(messages))
await combat.final()
else:
await ctx.send("No valid options found.")
@init.command()
async def status(self, ctx, name: str, *, args: str = ''):
"""Gets the status of a combatant or group.
__Valid Arguments__
private - PMs the controller of the combatant a more detailed status."""
combat = await Combat.from_ctx(ctx)
combatant = await combat.select_combatant(name, select_group=True)
if combatant is None:
await ctx.send("Combatant or group not found.")
return
private = 'private' in args.lower()
if not isinstance(combatant, CombatantGroup):
private = private and str(ctx.author.id) == combatant.controller
status = combatant.get_status(private=private)
if private and isinstance(combatant, MonsterCombatant):
status = f"{status}\n* This creature is a {combatant.monster_name}."
else:
status = "\n".join([co.get_status(private=private and str(ctx.author.id) == co.controller) for co in
combatant.get_combatants()])
if private:
controller = ctx.guild.get_member(int(combatant.controller))
if controller:
await controller.send("```markdown\n" + status + "```")
else:
await ctx.send("```markdown\n" + status + "```")
@staticmethod
async def _send_hp_result(ctx, combatant, delta=None):
deltaend = f" ({delta})" if delta else ""
if combatant.is_private:
await ctx.send(f"{combatant.name}: {combatant.hp_str()}")
try:
controller = ctx.guild.get_member(int(combatant.controller))
await controller.send(f"{combatant.name}'s HP: {combatant.hp_str(True)}{deltaend}")
except:
pass
else:
await ctx.send(f"{combatant.name}: {combatant.hp_str()}{deltaend}")
@init.group(invoke_without_command=True)
async def hp(self, ctx, name: str, *, hp: str = None):
"""Modifies the HP of a combatant."""
combat = await Combat.from_ctx(ctx)
combatant = await combat.select_combatant(name)
if combatant is None:
return await ctx.send("Combatant not found.")
if hp is None:
await ctx.send(f"{combatant.name}: {combatant.hp_str()}")
if combatant.is_private:
try:
controller = ctx.guild.get_member(int(combatant.controller))
await controller.send(f"{combatant.name}'s HP: {combatant.hp_str(True)}")
except:
pass
return
# i hp NAME mod X does not call i hp mod NAME X - handle this
if hp.startswith('mod '):
return await ctx.invoke(self.init_hp_mod, name=name, hp=hp[4:])
elif hp.startswith('set '):
return await ctx.invoke(self.init_hp_set, name=name, hp=hp[4:])
elif hp.startswith('max ') or hp == 'max':
return await ctx.invoke(self.init_hp_max, name=name, hp=hp[3:].strip())
hp_roll = roll(hp)
if combatant.hp is None:
combatant.set_hp(0)
combatant.modify_hp(hp_roll.total)
await combat.final()
if 'd' in hp:
delta = hp_roll.result
else:
delta = f"{hp_roll.total:+}"
await self._send_hp_result(ctx, combatant, delta)
@hp.command(name='max')
async def init_hp_max(self, ctx, name, *, hp: str = None):
"""Sets a combatant's max HP, or sets HP to max if no max is given."""
combat = await Combat.from_ctx(ctx)
combatant = await combat.select_combatant(name)
if combatant is None:
return await ctx.send("Combatant not found.")
delta = None
if not hp:
before = combatant.hp or 0
combatant.set_hp(combatant.max_hp)
delta = f"{combatant.hp - before:+}"
else:
hp_roll = roll(hp)
if hp_roll.total < 1:
return await ctx.send("You can't have a negative max HP!")
combatant.max_hp = hp_roll.total
await combat.final()
await self._send_hp_result(ctx, combatant, delta)
@hp.command(name='mod', hidden=True)
async def init_hp_mod(self, ctx, name, *, hp):
"""Modifies a combatant's current HP."""
await ctx.invoke(self.hp, name=name, hp=hp)
@hp.command(name='set')
async def init_hp_set(self, ctx, name, *, hp):
"""Sets a combatant's HP to a certain value."""
combat = await Combat.from_ctx(ctx)
combatant = await combat.select_combatant(name)
if combatant is None:
return await ctx.send("Combatant not found.")
before = combatant.hp or 0
hp_roll = roll(hp)
combatant.set_hp(hp_roll.total)
await combat.final()
await self._send_hp_result(ctx, combatant, f"{combatant.hp - before:+}")
@init.command()
async def thp(self, ctx, name: str, *, thp: str):
"""Modifies the temporary HP of a combatant.
Usage: !init thp <NAME> <HP>
Sets the combatants' THP if hp is positive, modifies it otherwise (i.e. `!i thp Avrae 5` would set Avrae's THP to 5 but `!i thp Avrae -2` would remove 2 THP)."""
combat = await Combat.from_ctx(ctx)
combatant = await combat.select_combatant(name)
if combatant is None:
await ctx.send("Combatant not found.")
return
thp_roll = roll(thp)
value = thp_roll.total
if value >= 0:
combatant.temp_hp = value
else:
combatant.temp_hp += value
delta = ""
if 'd' in thp:
delta = f"({thp_roll.result})"
if combatant.is_private:
await ctx.send(f"{combatant.name}: {combatant.hp_str()}")
try:
controller = ctx.guild.get_member(int(combatant.controller))
await controller.send(f"{combatant.name}'s HP: {combatant.hp_str(True)} {delta}")
except:
pass
else:
await ctx.send(f"{combatant.name}: {combatant.hp_str()} {delta}")
await combat.final()
@init.command()
async def effect(self, ctx, target_name: str, effect_name: str, *args):
"""Attaches a status effect to a combatant.
[args] is a set of args that affects a combatant in combat.
See `!help init re` to remove effects.
__**Valid Arguments**__
-dur <duration> - Sets the duration of the effect, in rounds.
conc - Makes the effect require concentration. Will end any other concentration effects.
end - Makes the effect duration tick on the end of turn, rather than the beginning.
-t <target> - Specifies more combatant's to target, chainable (e.g., "-t or1 -t or2").
-parent <"[combatant]|[effect]"> - Sets a parent effect from a specified combatant.
__Attacks__
-b <bonus> - Adds a bonus to hit.
-d <damage> - Adds additional damage.
-attack <"[hit]|[damage]|[description]"> - Adds an attack to the combatant. The effect name will be the name of the attack. No [hit] will autohit (e.g., -attack "|1d6[fire]|")
__Resists__
-resist <damage type> - Gives the combatant resistance to the given damage type.
-immune <damage type> - Gives the combatant immunity to the given damage type.
-vuln <damage type> - Gives the combatant vulnerability to the given damage type.`-custom` - Makes a custom attack with 0 to hit and base damage. Use `-b` and `-d` to add damage and to hit.
-neutral <damage type> - Removes the combatant's immunity, resistance, or vulnerability to the given damage type.
__General__
-ac <ac> - modifies ac temporarily; adds if starts with +/- or sets otherwise.
-sb <save bonus> - Adds a bonus to all saving throws."""
combat = await Combat.from_ctx(ctx)
args = argparse(args)
targets = []
for i, t in enumerate([target_name] + args.get('t')):
target = await combat.select_combatant(t, f"Select target #{i + 1}.", select_group=True)
if isinstance(target, CombatantGroup):
targets.extend(target.get_combatants())
else:
targets.append(target)
duration = args.last('dur', -1, int)
conc = args.last('conc', False, bool)
end = args.last('end', False, bool)
parent = args.last('parent')
if parent is not None:
parent = parent.split('|', 1)
if not len(parent) == 2:
raise InvalidArgument("`parent` arg must be formatted `COMBATANT|EFFECT_NAME`")
p_combatant = await combat.select_combatant(parent[0],
choice_message="Select the combatant with the parented effect.")
parent = await p_combatant.select_effect(parent[1])
embed = EmbedWithAuthor(ctx)
for combatant in targets:
if effect_name.lower() in (e.name.lower() for e in combatant.get_effects()):
out = "Effect already exists."
else:
effect_obj = Effect.new(combat, combatant, duration=duration, name=effect_name, effect_args=args,
concentration=conc, tick_on_end=end)
result = combatant.add_effect(effect_obj)
if parent:
effect_obj.set_parent(parent)
out = f"Added effect {effect_name} to {combatant.name}."
if result['conc_conflict']:
conflicts = [e.name for e in result['conc_conflict']]
out += f"\nRemoved {', '.join(conflicts)} due to concentration conflict!"
embed.add_field(name=combatant.name, value=out)
await ctx.send(embed=embed)
await combat.final()
@init.command(name='re')
async def remove_effect(self, ctx, name: str, effect: str = None):
"""Removes a status effect from a combatant or group. Removes all if effect is not passed."""
combat = await Combat.from_ctx(ctx)
targets = []
target = await combat.select_combatant(name, select_group=True)
if isinstance(target, CombatantGroup):
targets.extend(target.get_combatants())
else:
targets.append(target)
out = ""
for combatant in targets:
if effect is None:
combatant.remove_all_effects()
out += f"All effects removed from {combatant.name}.\n"
else:
to_remove = await combatant.select_effect(effect)
children_removed = ""
if to_remove.children:
children_removed = f"Also removed {len(to_remove.children)} child effects.\n"
to_remove.remove()
out += f'Effect {to_remove.name} removed from {combatant.name}.\n{children_removed}'
await ctx.send(out)
await combat.final()
@init.group(aliases=['a'], invoke_without_command=True)
async def attack(self, ctx, atk_name, *, args=''):
"""Rolls an attack against another combatant.
__Valid Arguments__
-t "<target>" - Sets targets for the attack. You can pass as many as needed.
-t "<target>|<args>" - Sets a target, and also allows for specific args to apply to them. (e.g, -t "OR1|hit" to force the attack against OR1 to hit)
*adv/dis* - Give advantage or disadvantage to the attack roll(s).
*ea* - Elven Accuracy, double advantage on the attack roll.
*-b <bonus>* - Adds a bonus to hit.
-criton <value> - The number the attack crits on if rolled on or above.
*-d <damage>* - Adds additional damage.
*-c <damage>* - Adds additional damage for when the attack crits, not doubled.
-rr <value> - How many attacks to make at the target.
*-mi <value>* - Minimum value of each die on the damage roll.
*-resist <damage type>* - Gives the target resistance to the given damage type.
*-immune <damage type>* - Gives the target immunity to the given damage type.
*-vuln <damage type>* - Gives the target vulnerability to the given damage type.
*-neutral <damage type>* - Removes the targets immunity, resistance, or vulnerability to the given damage type.
*hit* - The attack automatically hits.
*miss* - The attack automatically misses.
*crit* - The attack automatically crits.
*max* - Maximizes damage rolls.
-h - Hides rolled values.
-phrase <phrase> - Adds flavor text.