-
Notifications
You must be signed in to change notification settings - Fork 0
/
seat_commands.py
1572 lines (1266 loc) · 54.4 KB
/
seat_commands.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
"""Heavily inspired by incnone's necrobot for racing crypt of the necrodancer.
"""
from __future__ import annotations
import itertools
import asyncio
from enum import Enum, auto
import typing
from typing import Optional, List, Any, Sequence
from dataclasses import dataclass
import discord # type: ignore
import seat_typing
import discord_game
from discord_game import (DiscordGame, GameState,
DiscordPlayer, BotPlayer, CommonPlayer)
# from player_game import Findable, Player, Proposal
import strings
OPTIONAL_STR = "Brackets around an argument means that it's optional."
OWNER_ID = 84627464709472256
REVEAL_TIME = 5
GameDict = typing.Dict[discord.TextChannel, DiscordGame]
class CommandException(seat_typing.SeatException):
def __init__(self, command: typing.Union[CommandType, CommandMessage],
message: str):
super().__init__('Error running `{}`: {}'.format(
command, message))
class ArgType:
def __init__(self, arg_type: type,
optional: bool = False,
defaultvalue: Any = None,
name: Optional[str] = None) -> None:
self.arg_type: type = arg_type
self.optional: bool = optional
self.defaultvalue: Any = defaultvalue
self.name = name
def __str__(self) -> str:
if self.name is not None:
name: str = self.name
else:
name = self.arg_type.__name__
if self.optional:
return '[{}]'.format(name)
return name
def convert(self, arg: str, **kwargs: Any) -> Any:
if arg == '' and self.optional:
return self.defaultvalue
if issubclass(self.arg_type, seat_typing.Findable):
return self.arg_type.find(arg, **kwargs)
# Gives "Too many arguments for "object" without cast
return typing.cast(type, self.arg_type)(arg)
class CommandMessage:
"""Wrapper for discord.message"""
def __init__(self, message: discord.message,
channel: seat_typing.SeatChannel) -> None:
self._message = message
self.author: discord.User = message.author
self.channel = channel
self.command: str = message.content.split(' ')[0][1:]
self.args: List[Any] = message.content.split(' ')[1:]
self.game: Optional[DiscordGame] = None
self.player: Optional[DiscordPlayer] = None
def __str__(self) -> str:
return self.command
@property
def author_is_admin(self) -> bool:
if self.author.id == OWNER_ID:
return True
if not isinstance(self.author, discord.Member):
return False
for role in self.author.roles:
if role.name.lower() == 'game admin':
return True
return False
def convert_arguments(self,
arg_types: Sequence[ArgType],
**kwargs: Any,
) -> typing.List[typing.Any]:
if len(self.args) > len(arg_types):
raise CommandException(self, 'Too many arguments.')
if len(self.args) < len([x for x in arg_types if not x.optional]):
raise CommandException(self, 'Too few arguments.')
new_args: List[Any] = []
for arg, arg_type in itertools.zip_longest(
self.args, arg_types, fillvalue=''):
try:
new_args.append(arg_type.convert(arg, **kwargs))
except ValueError:
raise CommandException(self, 'Invalid type for argument {}. '
'Not convertible to {}'.format(
arg, arg_type))
return new_args
def format_list_with_conjunction_and_comma(sequence: typing.Iterable[Any],
conjunction: str) -> str:
if not sequence:
raise NotImplementedError('Empty list.')
res = ''
str_sequence = list(map(str, sequence))
for seq in str_sequence[:-2]:
res += seq + ', '
if len(str_sequence) > 1:
res += '{} {} '.format(str_sequence[-2], conjunction)
return res + str_sequence[-1]
@dataclass
class Requirements:
public_only: bool = False
private_only: bool = False
admin_only: bool = False
game_only: bool = False
real_life_game_only: bool = False
not_active_player: bool = False
# implies game_only
valid_game_states: typing.Iterable[GameState] = GameState
player_only: bool = False
def human_readable(self) -> List[str]:
result = []
if self.public_only:
result.append('in a public channel')
if self.private_only:
result.append('in a private channel')
if self.admin_only:
result.append("you're an admin")
if self.not_active_player:
result.append("you're not a player in an active game")
if self.game_only or self.player_only:
result.append('there is a valid game')
if self.player_only:
result.append("you're a player in that game")
if self.valid_game_states != GameState:
result.append(
'the game is {}.'.format(
format_list_with_conjunction_and_comma(
self.valid_game_states, 'or')))
return result
class CommandTag(Enum):
INFO = auto()
MANAGEMENT = auto()
GAMEPLAY = auto()
OPTIONS = auto()
REALLIFE = auto()
ADMIN = auto()
class CommandType():
def __init__(self,
command_name: str,
*command_names: str,
games: Optional[GameDict] = None,
requirements: Requirements = Requirements(),
args: Sequence[ArgType] = (),
help_text: str = 'This command has no help text.',
tag: CommandTag
) -> None:
self.command_name_list = (command_name,) + command_names
self.games = games
self.requirements = requirements
self.args = args
self.help_text = help_text
self.tag = tag
def __str__(self) -> str:
return self.command_name
@property
def command_name(self) -> str:
return self.command_name_list[0]
@property
def help(self) -> str:
return '```{name}\n{arg_format}\n{help_text}```'.format(
name=self.command_name,
arg_format=self.arg_format,
help_text=self.help_text)
@property
def arg_format(self) -> str:
return '!{}{}'.format(
self.command_name,
''.join(' '+str(arg) for arg in self.args))
@property
def game_only(self) -> bool:
return (self.requirements.game_only
or self.requirements.player_only
or self.requirements.valid_game_states != GameState
or self.requirements.real_life_game_only) # TODO
@property
def player_only(self) -> bool:
return self.requirements.player_only
def _validate_channel(self,
channel: seat_typing.SeatChannel) -> None:
# channel can also be group dm
if self.requirements.public_only and not channel.is_public:
raise CommandException(self, 'Not a public channel.')
if (self.requirements.private_only and not channel.is_dm):
raise CommandException(self, 'Not a private channel.')
def matches(self, key: str) -> bool:
return key in self.command_name_list
async def execute(self, command: CommandMessage) -> None:
if self.requirements.admin_only and not command.author_is_admin:
raise CommandException(self,
'Called by non-admin {}'.format(
command.author.display_name))
self._validate_channel(command.channel)
if self.requirements.not_active_player and self.games:
for other_game in self.games.values():
if (command.author in other_game and other_game.state not in
(GameState.GAME_OVER, GameState.STOPPED)):
raise CommandException(
self, 'You are a player in an active game.')
if not self.game_only:
await self._do_execute(command)
return
game = self._find_game(command)
if not game:
raise CommandException(self, 'Found no game.')
self._validate_game_state(game.state)
command.game = game
if not self.player_only:
await self._do_execute(command)
return
player = self._find_player(command.author)
if not player:
raise CommandException(self,
'You are not a player in this game.')
if (player not in game and game.state not in
(GameState.GAME_OVER, GameState.STOPPED)):
raise CommandException(
self,
'You are already a player in a different active game')
command.player = player
await self._do_execute(command)
def _find_game(self, command: CommandMessage) -> Optional[DiscordGame]:
assert self.games is not None
if command.channel.is_public:
if command.channel in self.games:
return self.games[command.channel]
else:
for game in self.games.values():
if command.author in game:
return game
return None
def _find_player(self, author: discord.User,
game: Optional[DiscordGame] = None
) -> Optional[DiscordPlayer]:
assert self.games is not None
if game:
if author in game:
return game.discord_players[author]
for other_game in self.games.values():
if author in other_game:
return other_game.discord_players[author]
return None
def _validate_game_state(self, state: GameState) -> None:
if state not in self.requirements.valid_game_states:
raise CommandException(self, 'Invalid game state.')
async def _do_execute(self, command: CommandMessage) -> None:
raise NotImplementedError(
'{}: Called do_execute in the abstract '
'base class.'.format(command.command))
# Player commands
class Ready(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
player_only=True,
public_only=True,
valid_game_states=[GameState.CREATED])
help_text = ('Indicates that you are ready to begin the game. '
'The game begins when all players are ready.')
super().__init__(
'ready', 'r',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.MANAGEMENT
)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.player
assert command.game
if command.player.ready:
raise CommandException(
self, '{} already ready.'.format(command.player))
await command.game.ready(command.player)
class Unready(CommandType):
def __init__(self, games: GameDict) -> None:
help_text = (
'Indicates that you are no longer ready to begin the game. '
'If the game is starting due to all players being ready, game '
'start is canceled until all players are ready again.')
requirements = Requirements(
player_only=True,
public_only=True,
valid_game_states=[GameState.CREATED,
GameState.STARTING])
super().__init__('unready',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.MANAGEMENT
)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.player
assert command.game
if not command.player.ready:
raise CommandException(
self, '{} already unready.'.format(command.player))
await command.game.unready(command.player)
class ProposeSeatSwap(CommandType):
def __init__(self, games: GameDict) -> None:
help_text = (
'Propose a seat swap with another player, optionally bundling '
'a bribe of garnets.')
requirements = Requirements(
player_only=True,
private_only=True,
valid_game_states=[GameState.RUNNING])
args = (ArgType(CommonPlayer),
ArgType(int, optional=True, defaultvalue=0))
super().__init__('propose',
games=games,
requirements=requirements,
args=args,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
assert command.player
target: CommonPlayer
garnets: int
target, garnets = command.convert_arguments(
self.args, game=command.game)
if command.player == target:
raise CommandException(self, 'Cannot swap with yourself.')
# TODO: public swaps
command.player.add_proposal_to(target, garnets)
await command.player.send(
'Proposal sent to {target} offering {garnets} garnets.\n'
'Those garnets are locked up until either player cancels the '
'proposal.\n'
'You now have {player.garnets} garnets.\n'
'You can cancel the proposal with `!cancel.`'.format(
target=target,
garnets=garnets,
player=command.player))
await target.send(
'Proposal received from {player} offering {garnets}.'.format(
player=command.player,
garnets=garnets))
class AcceptSeatSwap(CommandType):
def __init__(self, games: GameDict) -> None:
help_text = (
'Accept an incoming proposal. If you have multiple proposals you '
'must specify from which player the proposal is.')
requirements = Requirements(
player_only=True,
private_only=True,
valid_game_states=(GameState.RUNNING,))
args = (ArgType(discord_game.Proposal, optional=True),) # TODO
super().__init__('accept', 'acceptproposal', 'acceptincoming',
games=games,
requirements=requirements,
args=args,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
assert command.player
proposal: discord_game.Proposal[discord_game.CommonPlayer] = (
command.convert_arguments(self.args, player=command.player)[0])
proposals = command.player.proposals
if not proposals:
raise CommandException(self, 'You have no incoming proposals.')
if proposal is None and len(proposals) != 1:
raise CommandException(
self, 'You have multiple incoming proposals, '
'please specify from which player.')
if proposal is not None:
if proposal.target != command.player:
raise CommandException(
self, 'You can only accept proposals others sent to you.')
source = proposal.source
else: # len(proposals) == 1:
proposal = proposals[0]
source = proposal.source
if source.swapped:
await source.send(
'{} tried accepting your proposal, but you have already '
'swapped.'
'Proposal canceled.'.format(
command.player))
command.player.cancel_proposal(proposal)
raise CommandException(
self, '{} has already swapped this round. Proposal canceled.'
''.format(source))
command.player.accept_proposal(proposal)
await command.player.send(
'Accepted proposal from {source}, gaining {garnets} garnets.\n'
'You now have {player.garnets} garnets.\n'
'Your new seat is {player.seat}.\n'
"{source}'s new seat is {source.seat}.\n" .format(
player=command.player,
source=source,
garnets=proposal.garnets))
await source.send(
'{player} accepted your proposal, gaining {garnets} garnets.\n'
'Your new seat is {source.seat}.\n'
"{player}'s new seat is {player.seat}.\n".format(
player=command.player,
source=source,
garnets=proposal.garnets))
class CancelSeatSwap(CommandType):
def __init__(self, games: GameDict) -> None:
help_text = (
'Cancel a proposal. If you have multiple proposals you '
'must specify with which player the proposal is.')
requirements = Requirements(
player_only=True,
private_only=True,
valid_game_states=(GameState.RUNNING,))
args = (ArgType(discord_game.Proposal, optional=True),)
super().__init__('cancel', 'reject',
'cancelproposal', 'rejectproposal',
games=games,
requirements=requirements,
args=args,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
assert command.player
proposal: discord_game.Proposal[discord_game.CommonPlayer] = (
command.convert_arguments(self.args, player=command.player)[0])
proposals = command.player.proposals
if not proposals:
raise CommandException(self, 'You have no proposals.')
if proposal is None and len(proposals) != 1:
raise CommandException(
self, 'You have multiple incoming proposals, '
'please specify from which player.')
if proposal is None:
proposal = proposals[0]
if proposal.source == command.player:
other = proposal.target
else:
other = proposal.source
command.player.cancel_proposal(proposal)
await command.player.send(
'Canceled proposal with {}.'.format(other))
await other.send(
'{} canceled their proposal with you.'.format(command.player))
class CreateBotSwap(CommandType):
def __init__(self, games: GameDict) -> None:
help_text = (
'Propose a seat swap between two bots, optionally bundling '
'a bribe of garnets. Your bribe must be higher than either bots '
'highest offer for them to accept it, unless neither has any '
'offers. If several botswaps have the same bribe they\'re '
'resolved in a random order.\n'
'If you propose a botswap listing the same bot twice, that is '
'interpreted as a bribe for the bot to stay still and not accept '
'any other proposals. The bribe still needs to exceed other '
'proposals.')
requirements = Requirements(
player_only=True,
private_only=True,
valid_game_states=[GameState.RUNNING])
args = (ArgType(BotPlayer),
ArgType(BotPlayer),
ArgType(int, optional=True, defaultvalue=0))
super().__init__('botswap', 'proposebotswap',
games=games,
requirements=requirements,
args=args,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
assert command.player
source: BotPlayer
target: BotPlayer
garnets: int
source, target, garnets = (
command.convert_arguments(self.args, game=command.game))
botswaps = [
x for x in command.player.botswaps
if source in x and target in x]
if botswaps:
raise CommandException(
self, 'Found a botswap between {} and {} sponsored by you.'
''.format(source, target))
botswap = discord_game.BotSwap(
source, target, command.player, garnets)
command.player.add_botswap(botswap)
await command.player.send(
'Created: {}'.format(botswap))
class CancelBotSwap(CommandType):
def __init__(self, games: GameDict) -> None:
help_text = 'Cancel a proposed seat swap between two bots'
requirements = Requirements(
player_only=True,
private_only=True,
valid_game_states=[GameState.RUNNING])
args = (ArgType(BotPlayer),
ArgType(BotPlayer))
super().__init__('cancelbotswap',
games=games,
requirements=requirements,
args=args,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
assert command.player
source: BotPlayer
target: BotPlayer
source, target = command.convert_arguments(self.args,
game=command.game)
try:
botswap = next(x for x in command.player.botswaps
if (source in x and target in x))
except StopIteration:
raise CommandException(
self, 'Found no botswaps between {} and {} sponsored by you.'
''.format(source, target))
command.player.cancel_botswap(botswap)
await command.player.send(
'Canceled: {}'.format(botswap))
class DonateGarnets(CommandType):
def __init__(self, games: GameDict) -> None:
help_text = (
'Donate a number of garnets to a player.')
requirements = Requirements(
player_only=True,
private_only=True,
valid_game_states=[GameState.RUNNING])
args = (ArgType(CommonPlayer),
ArgType(int))
super().__init__('donate', 'donategarnets',
games=games,
requirements=requirements,
args=args,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.player
target: CommonPlayer
garnets: int
target, garnets = command.convert_arguments(self.args,
game=command.game)
await command.player.donate_garnets(target, garnets)
await command.player.send(
'You have sent {garnets} garnets to {target}.\n'
'You now have {player.garnets} garnets.'.format(
garnets=garnets,
target=target,
player=command.player))
await target.send(
'{player} has sent {garnets} garnets to you.\n'
'You now have {target.garnets} garnets.'.format(
garnets=garnets,
target=target,
player=command.player))
# Game info
class PrintProposals(CommandType):
def __init__(self, games: GameDict) -> None:
help_text = 'List all your incoming and outgoing proposals.'
requirements = Requirements(
player_only=True,
private_only=True,
valid_game_states=(GameState.RUNNING, GameState.PAUSED))
super().__init__('proposals',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
assert command.player
if not command.player.proposals:
await command.player.send(
'You have no incoming or outgoing proposals.')
return
await command.player.send(
*(str(x) for x in command.player.proposals),
start='```\n',
end='```',
sep='\n')
class PrintBotSwaps(CommandType):
def __init__(self, games: GameDict) -> None:
help_text = 'Print all botswaps sponsored by you.'
requirements = Requirements(
player_only=True,
private_only=True,
valid_game_states=[GameState.RUNNING])
super().__init__('botswaps', 'printbotswaps',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
assert command.player
if not command.player.botswaps:
await command.player.send("Found no botswaps sponsored by you.")
return
await command.player.send(
command.player.botswaps, start='```\n', end='```', sep='\n')
class PrintPlayers(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
game_only=True)
help_text = ('List players that have joined.')
super().__init__('players', 'listplayers',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
if not list(command.game.players):
await command.game.send('No players joined.')
return
await command.channel.send(*command.game.players, sep='\n',
start='```\n', end='```')
class PrintGarnets(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
game_only=True,
player_only=True)
help_text = ('Print how many garnets you have.')
super().__init__('garnets', 'printgarnets', 'garnet',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.player
await command.player.send(command.player.garnets)
class PrintSeating(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
game_only=True,
player_only=True,
valid_game_states=[GameState.RUNNING,
GameState.PAUSED,
GameState.GAME_OVER,
GameState.STOPPED])
help_text = ('Print seat and assigned numbers for all players.')
super().__init__('seating', 'printseating',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
assert command.player
assigned_numbers = command.player.assigned_numbers
await command.player.send(
'\n'.join(
'{0} {1:>2} {2}'.format(
player.seat,
assigned_numbers.get(player, ''),
player)
for player in command.game.players),
start='```', end='```',
)
class AssignNumber(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
game_only=True,
player_only=True)
help_text = ('Assign a deduced number to a player. '
'For use with `!seating`')
args = (ArgType(CommonPlayer),
ArgType(int))
super().__init__('assign', 'assignnumber',
games=games,
requirements=requirements,
args=args,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
assert command.player
target: CommonPlayer
number: seat_typing.PrivateNumber
target, number = command.convert_arguments(self.args,
game=command.game)
command.player.assigned_numbers[target] = number
await command.player.send('Assigned {} to {}.'.format(
target, number))
class UnassignNumber(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
game_only=True,
player_only=True)
help_text = ('Remove the assigned number from a player. '
'For use with `!seating`')
args = (ArgType(CommonPlayer),)
super().__init__('unassign', 'unassignnumber',
games=games,
requirements=requirements,
args=args,
help_text=help_text,
tag=CommandTag.GAMEPLAY)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
assert command.player
target: CommonPlayer = command.convert_arguments(
self.args, game=command.game)[0]
number = command.player.assigned_numbers.pop(target)
await command.player.send('Unassigned {} from {}.'.format(
number, command.args[0]))
# Game management commands
class Create(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
public_only=True)
help_text = ('Creates a seat game.')
super().__init__('create',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.MANAGEMENT)
async def _do_execute(self, command: CommandMessage) -> None:
assert self.games is not None
if self._find_game(command):
raise CommandException(self, 'game already running.')
game = DiscordGame(command.channel, {})
self.games[command.channel] = game
await game.send(
'Game created. Game will start when all players are `!ready` and '
'at least {} players, of which {} human, have joined.'.format(
discord_game.MIN_PLAYERS,
discord_game.MIN_HUMAN_PLAYERS))
class Recreate(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
public_only=True,
game_only=True,
valid_game_states=(
GameState.GAME_OVER,
GameState.STOPPED))
help_text = ("Recreates a finished game with the same options.")
super().__init__('recreate',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.MANAGEMENT)
async def _do_execute(self, command: CommandMessage) -> None:
assert self.games is not None
assert command.game
game = DiscordGame(command.channel, command.game.options)
self.games[command.channel] = game
await game.send(
'Game recreated with the same options. Game will start when all '
'players are `!ready`.')
class Join(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
public_only=True,
game_only=True,
not_active_player=True,
valid_game_states=(
GameState.CREATED,
GameState.STARTING))
help_text = 'Join a created game.'
super().__init__('join',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.MANAGEMENT)
async def _do_execute(self, command: CommandMessage) -> None:
assert command.game
await command.game.add_user(command.author)
class CreateJoin(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
public_only=True,
not_active_player=True)
help_text = ('Creates and joins a game if there is none.')
super().__init__('createjoin', 'join',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.MANAGEMENT)
async def _do_execute(self, command: CommandMessage) -> None:
assert self.games is not None
if self._find_game(command):
raise CommandException(self, 'game already running.')
game = DiscordGame(command.channel, {})
self.games[command.channel] = game
await game.send(
'Game created. Game will start when all players are `!ready`.')
await game.add_user(command.author)
class RecreateJoin(CommandType):
def __init__(self, games: GameDict) -> None:
requirements = Requirements(
public_only=True,
game_only=True,
not_active_player=True,
valid_game_states=(
GameState.GAME_OVER,
GameState.STOPPED))
help_text = ("Recreates a finished game and joins it.")
super().__init__('recreatejoin', 'join',
games=games,
requirements=requirements,
help_text=help_text,
tag=CommandTag.MANAGEMENT)
async def _do_execute(self, command: CommandMessage) -> None:
assert self.games is not None
assert command.game
game = DiscordGame(command.channel, command.game.options)
self.games[command.channel] = game
await game.add_user(command.author)
await game.send(
'Game recreated with the same options. Game will start when all '
'players are `!ready`.')
class Leave(CommandType):
def __init__(self, games: GameDict) -> None:
help_text = 'Leave a game. Cannot leave a game in progress.'