-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathTeamVersusMatch.cs
More file actions
7635 lines (6426 loc) · 318 KB
/
TeamVersusMatch.cs
File metadata and controls
7635 lines (6426 loc) · 318 KB
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
using CommunityToolkit.HighPerformance.Buffers;
using Microsoft.Extensions.ObjectPool;
using OpenSkillSharp;
using OpenSkillSharp.Models;
using SS.Core;
using SS.Core.ComponentAdvisors;
using SS.Core.ComponentCallbacks;
using SS.Core.ComponentInterfaces;
using SS.Core.Map;
using SS.Matchmaking.Advisors;
using SS.Matchmaking.Callbacks;
using SS.Matchmaking.Interfaces;
using SS.Matchmaking.League;
using SS.Matchmaking.Queues;
using SS.Matchmaking.TeamVersus;
using SS.Packets.Game;
using SS.Replay;
using SS.Utilities;
using SS.Utilities.ObjectPool;
using System.Buffers;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Text.Json;
namespace SS.Matchmaking.Modules
{
/// <summary>
/// Module for team versus matches where the # of teams and # of players per team can be configured.
/// </summary>
/// <remarks>
/// Win conditions:
/// - last team standing
/// - a team is eliminated when all its players are knocked out (no remaining lives)
/// - (alternatively) a team is eliminated if none of its players remain in the play area (respawn area separate from play area), like in 2v2
/// - match time limit hit and one team has a higher # of lives remaining
/// - in overtime and a kill is made
///
/// Subbing (IDEA)
/// -------
/// If a player leaves or goes to spec during a game, they have 30 seconds to ?return, after which their spot is forfeit and can be subbed.
/// Players that leave their game in this manner can be penalized (disallow queuing for a certain timeframe, 10 minutes?).
/// Alternatively, a player can request to be subbed (no penalization if someone subs).
/// A player that subs in does not lose their spot in the queue. They can effectively be at the front of the queue when the game ends and get to play in the next game.
///
/// Time limit
/// ----------
/// 30 minutes,
/// then 5 minutes of overtime (next kill wins),
/// then maybe sudden death - burn items, lower max energy of each player by 1 unit every minute until at the minimum max energy, then lower max recharge rate of each player by 1 every minute
/// </remarks>
[ModuleInfo($"""
Manages team versus matches.
Configuration: {nameof(TeamVersusMatch)}.conf
""")]
public sealed class TeamVersusMatch : IAsyncModule, IMatchmakingQueueAdvisor, IFreqManagerEnforcerAdvisor, IMatchFocusAdvisor, ILeagueGameMode, ILeagueHelp
{
private const string ConfigurationFileName = "TeamVersus.conf";
private readonly IComponentBroker _broker;
private readonly IArenaManager _arenaManager;
private readonly ICapabilityManager _capabilityManager;
private readonly IChat _chat;
private readonly IClientSettings _clientSettings;
private readonly ICommandManager _commandManager;
private readonly IConfigManager _configManager;
private readonly IGame _game;
private readonly ILogManager _logManager;
private readonly IMainloop _mainloop;
private readonly IMainloopTimer _mainloopTimer;
private readonly IMapData _mapData;
private readonly IMatchFocus _matchFocus;
private readonly IMatchmakingQueues _matchmakingQueues;
private readonly INetwork _network;
private readonly IObjectPoolManager _objectPoolManager;
private readonly IPlayerData _playerData;
private readonly IPrng _prng;
// optional
private ITeamVersusStatsBehavior? _teamVersusStatsBehavior;
private ILeagueManager? _leagueManager;
private IReplayController? _replayController;
private AdvisorRegistrationToken<IMatchFocusAdvisor>? _iMatchFocusAdvisorToken;
private AdvisorRegistrationToken<IMatchmakingQueueAdvisor>? _iMatchmakingQueueAdvisorToken;
private ConfigHandle? _teamVersusConfig;
private PlayerDataKey<PlayerData> _pdKey;
private ClientSettingIdentifier _killEnterDelayClientSettingId;
private readonly ClientSettingIdentifier[] _spawnXClientSettingIds = new ClientSettingIdentifier[4];
private readonly ClientSettingIdentifier[] _spawnYClientSettingIds = new ClientSettingIdentifier[4];
private readonly ClientSettingIdentifier[] _spawnRadiusClientSettingIds = new ClientSettingIdentifier[4];
private TimeSpan _abandonStartPenaltyDuration = TimeSpan.FromMinutes(5);
private TimeSpan _notReadyStartPenaltyDuration = TimeSpan.FromMinutes(3);
/// <summary>
/// Dictionary of queues.
/// </summary>
/// <remarks>
/// key: queue name
/// </remarks>
private readonly Dictionary<string, TeamVersusMatchmakingQueue> _queueDictionary = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Match configurations by queue.
/// </summary>
/// <remarks>
/// key: queue name
/// </remarks>
private readonly Dictionary<string, List<MatchConfiguration>> _queueMatchConfigurations = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Match configurations for league matches by GameTypeId.
/// </summary>
/// <remarks>
/// Key: GameTypeId
/// </remarks>
private readonly Dictionary<long, MatchConfiguration> _leagueMatchConfigurations = [];
/// <summary>
/// Dictionary of match configurations.
/// </summary>
/// <remarks>
/// key: match type
/// </remarks>
private readonly Dictionary<string, MatchConfiguration> _matchConfigurationDictionary = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Dictionary of matches.
/// </summary>
private readonly Dictionary<MatchIdentifier, MatchData> _matchDataDictionary = [];
/// <summary>
/// Dictionary for looking up what slot in a match a player is associated with.
/// <para>
/// A player stays associated with a match until the match ends, regardless of if the player left the match or was subbed out.
/// </para>
/// </summary>
/// <remarks>
/// key: player name
/// </remarks>
private readonly Dictionary<string, PlayerSlot> _playerSlotDictionary = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Slots that are available for substitute players.
/// </summary>
private readonly LinkedList<PlayerSlot> _availableSubSlots = new();
/// <summary>
/// Data per arena base name (shared among arenas with the same base name).
/// Only contains data for arena base names that are configured for matches.
/// </summary>
/// <remarks>
/// Key: Arena base name
/// </remarks>
private readonly Dictionary<string, ArenaBaseData> _arenaBaseDataDictionary = [];
/// <summary>
/// Data per-arena (not all arenas, only those configured for matches).
/// </summary>
private readonly Dictionary<Arena, ArenaData> _arenaDataDictionary = [];
private readonly DefaultObjectPool<ArenaData> _arenaDataPool = new(new DefaultPooledObjectPolicy<ArenaData>(), Constants.TargetArenaCount);
private readonly DefaultObjectPool<TeamLineup> _teamLineupPool = new(new DefaultPooledObjectPolicy<TeamLineup>(), Constants.TargetPlayerCount);
private readonly DefaultObjectPool<List<TeamLineup>> _teamLineupListPool = new(new ListPooledObjectPolicy<TeamLineup>(), 8);
private readonly DefaultObjectPool<List<Player>> _playerListPool = new(new ListPooledObjectPolicy<Player>() { InitialCapacity = Constants.TargetPlayerCount }, 8);
public TeamVersusMatch(
IComponentBroker broker,
IArenaManager arenaManager,
ICapabilityManager capabilityManager,
IChat chat,
IClientSettings clientSettings,
ICommandManager commandManager,
IConfigManager configManager,
IGame game,
ILogManager logManager,
IMainloop mainloop,
IMainloopTimer mainloopTimer,
IMapData mapData,
IMatchFocus matchFocus,
IMatchmakingQueues matchmakingQueues,
INetwork network,
IObjectPoolManager objectPoolManager,
IPlayerData playerData,
IPrng prng)
{
_broker = broker ?? throw new ArgumentNullException(nameof(broker));
_arenaManager = arenaManager ?? throw new ArgumentNullException(nameof(arenaManager));
_capabilityManager = capabilityManager ?? throw new ArgumentNullException(nameof(capabilityManager));
_chat = chat ?? throw new ArgumentNullException(nameof(chat));
_clientSettings = clientSettings ?? throw new ArgumentNullException(nameof(clientSettings));
_commandManager = commandManager ?? throw new ArgumentNullException(nameof(commandManager));
_configManager = configManager ?? throw new ArgumentNullException(nameof(configManager));
_game = game ?? throw new ArgumentNullException(nameof(game));
_logManager = logManager ?? throw new ArgumentNullException(nameof(logManager));
_mainloop = mainloop ?? throw new ArgumentNullException(nameof(mainloop));
_mainloopTimer = mainloopTimer ?? throw new ArgumentNullException(nameof(mainloopTimer));
_mapData = mapData ?? throw new ArgumentNullException(nameof(mapData));
_matchFocus = matchFocus ?? throw new ArgumentNullException(nameof(matchFocus));
_matchmakingQueues = matchmakingQueues ?? throw new ArgumentNullException(nameof(matchmakingQueues));
_network = network ?? throw new ArgumentNullException(nameof(network));
_objectPoolManager = objectPoolManager ?? throw new ArgumentNullException(nameof(objectPoolManager));
_playerData = playerData ?? throw new ArgumentNullException(nameof(playerData));
_prng = prng ?? throw new ArgumentNullException(nameof(prng));
}
#region Module members
async Task<bool> IAsyncModule.LoadAsync(IComponentBroker broker, CancellationToken cancellationToken)
{
_teamVersusStatsBehavior = broker.GetInterface<ITeamVersusStatsBehavior>();
_leagueManager = broker.GetInterface<ILeagueManager>();
_replayController = broker.GetInterface<IReplayController>();
if (!_clientSettings.TryGetSettingsIdentifier("Kill", "EnterDelay", out _killEnterDelayClientSettingId))
{
return false;
}
if (!GetSpawnClientSettingIdentifiers())
{
return false;
}
_teamVersusConfig = await _configManager.OpenConfigFileAsync(null, ConfigurationFileName);
if (_teamVersusConfig is null)
{
_logManager.LogM(LogLevel.Error, nameof(TeamVersusMatch), $"Error opening config file {ConfigurationFileName}.");
return false;
}
if (!LoadConfiguration())
{
_logManager.LogM(LogLevel.Error, nameof(TeamVersusMatch), $"Error loading from config file {ConfigurationFileName}.");
_configManager.CloseConfigFile(_teamVersusConfig);
_teamVersusConfig = null;
return false;
}
_pdKey = _playerData.AllocatePlayerData<PlayerData>();
ArenaActionCallback.Register(broker, Callback_ArenaAction);
PlayerActionCallback.Register(broker, Callback_PlayerAction);
MatchmakingQueueChangedCallback.Register(broker, Callback_MatchmakingQueueChanged);
_commandManager.AddCommand("loadmatchtype", Command_loadmatchtype);
_commandManager.AddCommand("unloadmatchtype", Command_unloadmatchtype);
_iMatchFocusAdvisorToken = broker.RegisterAdvisor<IMatchFocusAdvisor>(this);
_iMatchmakingQueueAdvisorToken = broker.RegisterAdvisor<IMatchmakingQueueAdvisor>(this);
return true;
bool GetSpawnClientSettingIdentifiers()
{
Span<char> xKey = stackalloc char["Team#-X".Length];
Span<char> yKey = stackalloc char["Team#-Y".Length];
Span<char> rKey = stackalloc char["Team#-Radius".Length];
"Team#-X".CopyTo(xKey);
"Team#-Y".CopyTo(yKey);
"Team#-Radius".CopyTo(rKey);
for (int i = 0; i < 4; i++)
{
xKey[4] = yKey[4] = rKey[4] = (char)('0' + i);
if (!_clientSettings.TryGetSettingsIdentifier("Spawn", xKey, out _spawnXClientSettingIds[i]))
return false;
if (!_clientSettings.TryGetSettingsIdentifier("Spawn", yKey, out _spawnYClientSettingIds[i]))
return false;
if (!_clientSettings.TryGetSettingsIdentifier("Spawn", rKey, out _spawnRadiusClientSettingIds[i]))
return false;
}
return true;
}
}
Task<bool> IAsyncModule.UnloadAsync(IComponentBroker broker, CancellationToken cancellationToken)
{
if (!broker.UnregisterAdvisor(ref _iMatchFocusAdvisorToken))
return Task.FromResult(false);
if (!broker.UnregisterAdvisor(ref _iMatchmakingQueueAdvisorToken))
return Task.FromResult(false);
_commandManager.RemoveCommand("loadmatchtype", Command_loadmatchtype);
_commandManager.RemoveCommand("unloadmatchtype", Command_unloadmatchtype);
ArenaActionCallback.Unregister(broker, Callback_ArenaAction);
PlayerActionCallback.Unregister(broker, Callback_PlayerAction);
MatchmakingQueueChangedCallback.Unregister(broker, Callback_MatchmakingQueueChanged);
_playerData.FreePlayerData(ref _pdKey);
if (_teamVersusConfig is not null)
{
_configManager.CloseConfigFile(_teamVersusConfig);
_teamVersusConfig = null;
}
if (_teamVersusStatsBehavior is not null)
broker.ReleaseInterface(ref _teamVersusStatsBehavior);
if (_leagueManager is not null)
broker.ReleaseInterface(ref _leagueManager);
if (_replayController is not null)
broker.ReleaseInterface(ref _replayController);
return Task.FromResult(true);
}
#endregion
#region IFreqManagerEnforcerAdvsor
ShipMask IFreqManagerEnforcerAdvisor.GetAllowableShips(Player player, ShipType ship, short freq, StringBuilder? errorMessage)
{
if (!player.TryGetExtraData(_pdKey, out PlayerData? playerData))
return ShipMask.None;
Arena? arena = player.Arena;
if (arena is null || !_arenaDataDictionary.TryGetValue(arena, out ArenaData? arenaData))
return ShipMask.None;
bool isPublicPlayFreq = IsPublicPlayFreq(freq);
if (isPublicPlayFreq && !arenaData.PublicPlayEnabled)
{
errorMessage?.Append("This arena does not allow public play.");
return ShipMask.None;
}
MatchData? leagueMatch = arenaData.LeagueMatch;
if (leagueMatch is not null)
{
if (leagueMatch.Status == MatchStatus.Starting)
{
// Don't allow a change at this stage.
return player.Ship.GetShipMask();
}
if (isPublicPlayFreq)
{
if (leagueMatch.Status == MatchStatus.Initializing)
{
// Public play is allowed before the match starts.
return ShipMask.All;
}
else
{
errorMessage?.Append("There is an ongoing league match. Public play is unavailable for the duration.");
return ShipMask.None;
}
}
Team? team = null;
foreach (Team otherTeam in leagueMatch.Teams)
{
if (otherTeam.Freq == freq)
{
team = otherTeam;
break;
}
}
if (team is null)
return ShipMask.None;
if (leagueMatch.Status == MatchStatus.Initializing || leagueMatch.Status == MatchStatus.StartingCountdown)
{
// Special rules apply before the match starts since slots are not assigned until it actually starts.
return CanPlayAsStarterInLeagueMatch(arena, player, team) ? ShipMask.All : ShipMask.None;
}
}
PlayerSlot? playerSlot = playerData.AssignedSlot;
if (playerSlot is null)
{
// The player is not in a match.
if (leagueMatch is not null)
{
return ShipMask.None;
}
else
{
// Allow changing to any ship for public play.
return ShipMask.All;
}
}
else
{
// The player is in a match.
if (CanShipChangeNow(player, playerData))
{
// Set the player's next ship.
SetNextShip(player, playerData, ship, false);
// Allow changing to any ship.
return ShipMask.All;
}
else
{
// Not allowed to change ships right now.
// Set the player's next ship.
SetNextShip(player, playerData, ship, true);
// Only allow the current ship. In other words, no change allowed.
return player.Ship.GetShipMask();
}
}
}
bool IFreqManagerEnforcerAdvisor.CanChangeToFreq(Player player, short newFreq, StringBuilder? errorMessage)
{
if (!player.TryGetExtraData(_pdKey, out PlayerData? playerData))
return false;
Arena? arena = player.Arena;
if (arena is null || !_arenaDataDictionary.TryGetValue(arena, out ArenaData? arenaData))
return false;
bool isPublicPlayFreq = IsPublicPlayFreq(newFreq);
if (isPublicPlayFreq && !arenaData.PublicPlayEnabled)
{
errorMessage?.Append("This arena does not allow public play.");
return false;
}
if (arenaData.LeagueMatch is not null)
{
// The arena is reserved for a league match.
MatchData leagueMatch = arenaData.LeagueMatch;
if (isPublicPlayFreq)
{
if (leagueMatch.Status == MatchStatus.Initializing)
{
// Public play is allowed before the match starts.
return true;
}
else
{
errorMessage?.Append("There is an ongoing league match. Public play is unavailable for the duration.");
return false;
}
}
else
{
foreach (Team team in leagueMatch.Teams)
{
if (team.Freq == newFreq)
{
if (team.LeagueTeam is null)
continue;
// Check that the player is on the team's roster.
if (team.LeagueTeam.Roster.ContainsKey(player.Name!))
{
return true;
}
else
{
errorMessage?.Append($"You are not on the roster of: '{team.LeagueTeam.TeamName}'.");
return false;
}
}
}
errorMessage?.Append($"{newFreq} is not a valid freq for the league match.");
return false;
}
}
else
{
PlayerSlot? playerSlot = playerData.AssignedSlot;
if (playerSlot is not null)
{
if (newFreq == playerSlot.Team.Freq)
{
// In a match, always allow players to change to their team's freq.
return true;
}
if (playerSlot.Status != PlayerSlotStatus.KnockedOut)
{
// Only team freq is allowed.
errorMessage?.Append("Only the team freq is allowed when playing in a match.");
return false;
}
}
if (arenaData.PublicPlayEnabled)
{
if (!isPublicPlayFreq)
{
errorMessage?.Append("Only frequencies 0-9 are available for public play.");
}
return isPublicPlayFreq;
}
else
{
return false;
}
}
}
bool IFreqManagerEnforcerAdvisor.CanEnterGame(Player player, StringBuilder? errorMessage)
{
if (!player.TryGetExtraData(_pdKey, out PlayerData? playerData))
return false;
Arena? arena = player.Arena;
if (arena is null || !_arenaDataDictionary.TryGetValue(arena, out ArenaData? arenaData))
return false;
if (arenaData.LeagueMatch is not null)
{
// The arena is reserved for a league match.
if (arenaData.LeagueMatch.Status == MatchStatus.Initializing)
{
// The match has not started yet, so special rules apply.
if (arenaData.PublicPlayEnabled)
{
return true;
}
else
{
if (arenaData.LeagueMatch.TryGetLeagueTeam(player.Name, out _))
return true;
errorMessage?.Append("You are not on the roster of any team in this league match.");
return false;
}
}
PlayerSlot? playerSlot = playerData.AssignedSlot;
if (playerSlot is null)
{
return false;
}
else
{
if (player.Ship == ShipType.Spec)
{
// Allow returning to match using regular ship selection, rather than having to use ?return.
// This is pretty hacky, as it's trying to fit into the existing FreqManager's use of IFreqManagerEnforcerAdvisor to tie in.
ReturnToMatch(player, playerData);
}
return false;
}
}
else
{
PlayerSlot? playerSlot = playerData.AssignedSlot;
if (playerSlot is null)
{
// Not in a match. Can enter public play if the arena is configured for it.
if (!arenaData.PublicPlayEnabled)
{
errorMessage?.Append($"This arena does not support public play. Use ?{_matchmakingQueues.NextCommandName} to search for a match to play in.");
}
return arenaData.PublicPlayEnabled;
}
else
{
if (player.Ship == ShipType.Spec)
{
// Allow returning to match using regular ship selection, rather than having to use ?return.
// This is pretty hacky, as it's trying to fit into the existing FreqManager's use of IFreqManagerEnforcerAdvisor to tie in.
ReturnToMatch(player, playerData);
}
return false;
}
}
}
bool IFreqManagerEnforcerAdvisor.IsUnlocked(Player player, StringBuilder? errorMessage)
{
return true;
}
#endregion
#region IMatchFocusAdvisor
bool IMatchFocusAdvisor.TryGetPlaying(IMatch match, HashSet<string> players)
{
if (match is null || match is not MatchData matchData)
return false;
foreach (var team in matchData.Teams)
{
foreach (var slot in team.Slots)
{
if (slot.PlayerName is not null)
{
players.Add(slot.PlayerName);
}
}
}
return true;
}
IMatch? IMatchFocusAdvisor.GetMatch(Player player)
{
if (player is null || !player.TryGetExtraData(_pdKey, out PlayerData? playerData))
return null;
return playerData.AssignedSlot?.MatchData;
}
#endregion
#region ILeagueGameMode
ILeagueMatch? ILeagueGameMode.CreateMatch(LeagueGameInfo leagueGame)
{
if (!_leagueMatchConfigurations.TryGetValue(leagueGame.GameTypeId, out MatchConfiguration? matchConfiguration))
return null;
if (!TryGetAvailableMatch(matchConfiguration, leagueGame, out MatchData? matchData))
return null;
//
// Reserve the match.
//
matchData.Status = MatchStatus.Initializing;
// Send a chat notification to the entire zone.
StringBuilder announcementBuilder = _objectPoolManager.StringBuilderPool.Get();
try
{
AppendLeagueMatchInfo(announcementBuilder, matchData);
announcementBuilder.Append($" -- Starting in ?go {matchData.ArenaName}");
_chat.SendArenaMessage(null, announcementBuilder);
}
finally
{
_objectPoolManager.StringBuilderPool.Return(announcementBuilder);
}
Arena? arena = matchData.Arena;
if (arena is not null)
{
// The arena already exists. Adjust ships and freqs.
// Move everyone in the arena to spec.
// Move players on teams to their respective freq.
foreach (Player player in _playerData.Players)
{
if (player.Arena != arena)
continue;
matchData.TryGetLeagueTeam(player.Name, out Team? team);
bool changeShip = player.Ship != ShipType.Spec;
short? newFreq = team is null
? player.Freq != arena.SpecFreq ? arena.SpecFreq : null
: player.Freq != team.Freq ? team.Freq : null;
if (newFreq is not null)
{
if (changeShip)
_game.SetShipAndFreq(player, ShipType.Spec, newFreq.Value);
else
_game.SetFreq(player, newFreq.Value);
}
else if (changeShip)
{
_game.SetShip(player, ShipType.Spec);
}
}
}
return matchData;
}
bool ILeagueGameMode.CancelMatch(ILeagueMatch match)
{
if (match is not MatchData matchData)
{
return false;
}
if (matchData.Status == MatchStatus.Initializing)
{
Arena? arena = matchData.Arena;
EndMatch(matchData, MatchEndReason.Cancelled, null);
if (arena is not null)
{
_chat.SendArenaMessage(arena, "League match cancelled.");
}
return true;
}
return false;
}
#endregion
#region ILeagueHelp
void ILeagueHelp.PrintHelp(Player player)
{
_chat.SendMessage(player, "--- Match Information ---------------------------------------------------------");
PrintCommand(player, CommandNames.MatchInfo, "Prints information about the current match.");
PrintCommand(player, CommandNames.Rosters, "Prints the team rosters of the current match.");
_chat.SendMessage(player, "--- Team Members --------------------------------------------------------------");
PrintCommand(player, CommandNames.RequestSub, "Makes your slot available for subbing.");
PrintCommand(player, CommandNames.Sub, "To fill an empty slot or to sub in for another player.");
PrintCommand(player, CommandNames.CancelSub, "To cancel an ongoing attempt to sub in for another player.");
PrintCommand(player, CommandNames.Cap, "To take captain powers for your the freq you are on.");
_chat.SendMessage(player, "--- Captains ------------------------------------------------------------------");
PrintCommand(player, CommandNames.Ready, "Toggles the indicator on whether your team is ready.");
PrintCommand(player, CommandNames.AllowPlay, "Toggles starters. Who can play (in a ship) before GO.");
PrintCommand(player, CommandNames.AllowSub, "Toggles whether a player can ?sub in after GO.");
PrintCommand(player, CommandNames.FullSub, "Toggles whether a slot is enabled for a full sub.");
PrintCommand(player, CommandNames.RequestSub, "Makes the targeted slot available for subbing.");
if (_capabilityManager.HasCapability(player, Constants.Capabilities.IsStaff))
{
_chat.SendMessage(player, "--- Staff ---------------------------------------------------------------------");
PrintCommand(player, CommandNames.ForceStart, "Forces a league match to start.");
}
void PrintCommand(Player player, string command, string description)
{
_chat.SendMessage(player, $"?{command,-16} {description}");
}
}
#endregion
#region Callbacks
[ConfigHelp<bool>("SS.Matchmaking.TeamVersusMatch", "PublicPlayEnabled", ConfigScope.Arena, Default = false,
Description = "Whether to allow players into ships without being in a match.")]
private void Callback_ArenaAction(Arena arena, ArenaAction action)
{
bool isRegisteredArena = false;
foreach (MatchConfiguration configuration in _matchConfigurationDictionary.Values)
{
if (string.Equals(arena.BaseName, configuration.ArenaBaseName, StringComparison.OrdinalIgnoreCase))
{
isRegisteredArena = true;
break;
}
}
if (!isRegisteredArena)
return;
if (action == ArenaAction.Create)
{
ConfigHandle ch = arena.Cfg!;
ArenaData arenaData = _arenaDataPool.Get();
_arenaDataDictionary.Add(arena, arenaData);
// Read ship settings from the config.
string[] shipNames = Enum.GetNames<ShipType>();
for (int i = 0; i < 8; i++)
{
arenaData.ShipSettings[i] = new ShipSettings()
{
InitialBurst = (byte)_configManager.GetInt(ch, shipNames[i], "InitialBurst", 0),
InitialRepel = (byte)_configManager.GetInt(ch, shipNames[i], "InitialRepel", 0),
InitialThor = (byte)_configManager.GetInt(ch, shipNames[i], "InitialThor", 0),
InitialBrick = (byte)_configManager.GetInt(ch, shipNames[i], "InitialBrick", 0),
InitialDecoy = (byte)_configManager.GetInt(ch, shipNames[i], "InitialDecoy", 0),
InitialRocket = (byte)_configManager.GetInt(ch, shipNames[i], "InitialRocket", 0),
InitialPortal = (byte)_configManager.GetInt(ch, shipNames[i], "InitialPortal", 0),
MaximumEnergy = (short)_configManager.GetInt(ch, shipNames[i], "MaximumEnergy", 0),
};
}
arenaData.PublicPlayEnabled = _configManager.GetBool(ch, "SS.Matchmaking.TeamVersusMatch", "PublicPlayEnabled", false);
// Register callbacks.
KillCallback.Register(arena, Callback_Kill);
PreShipFreqChangeCallback.Register(arena, Callback_PreShipFreqChange);
ShipFreqChangeCallback.Register(arena, Callback_ShipFreqChange);
PlayerPositionPacketCallback.Register(arena, Callback_PlayerPositionPacket);
BricksPlacedCallback.Register(arena, Callback_BricksPlaced);
SpawnCallback.Register(arena, Callback_Spawn);
// Register commands.
_commandManager.AddCommand(CommandNames.RequestSub, Command_requestsub, arena);
_commandManager.AddCommand(CommandNames.Sub, Command_sub, arena);
_commandManager.AddCommand(CommandNames.CancelSub, Command_cancelsub, arena);
_commandManager.AddCommand(CommandNames.Return, Command_return, arena);
//_commandManager.AddCommand(CommandNames.Restart, Command_restart, arena);
//_commandManager.AddCommand(CommandNames.Randomize, Command_randomize, arena);
//_commandManager.AddCommand(CommandNames.End, Command_end, arena);
//_commandManager.AddCommand(CommandNames.Draw, Command_draw, arena);
_commandManager.AddCommand(CommandNames.ShipChange, Command_sc, arena);
_commandManager.AddCommand(CommandNames.Items, Command_items, arena);
_commandManager.AddCommand(CommandNames.MatchInfo, Command_matchinfo, arena);
_commandManager.AddCommand(CommandNames.FreqInfo, Command_matchinfo, arena); // alias of ?matchinfo since existing 4v4 players accustomed to !freqinfo
_commandManager.AddCommand(CommandNames.Rosters, Command_rosters, arena);
_commandManager.AddCommand(CommandNames.Cap, Command_cap, arena);
_commandManager.AddCommand(CommandNames.Ready, Command_ready, arena);
_commandManager.AddCommand(CommandNames.Rdy, Command_ready, arena);
_commandManager.AddCommand(CommandNames.ForceStart, Command_forcestart, arena);
_commandManager.AddCommand(CommandNames.AllowPlay, Command_allowplay, arena);
_commandManager.AddCommand(CommandNames.AllowSub, Command_allowsub, arena);
_commandManager.AddCommand(CommandNames.FullSub, Command_fullsub, arena);
// Register advisors and interfaces.
arenaData.IFreqManagerEnforcerAdvisorToken = arena.RegisterAdvisor<IFreqManagerEnforcerAdvisor>(this);
arenaData.ILeagueHelpToken = arena.RegisterInterface<ILeagueHelp>(this, nameof(TeamVersusMatch));
// Fill in arena for associated matches.
foreach (MatchData matchData in _matchDataDictionary.Values)
{
if (matchData.Arena is null && string.Equals(arena.Name, matchData.ArenaName, StringComparison.OrdinalIgnoreCase))
{
matchData.Arena = arena;
// Also keep track of league matches in the ArenaData.
if (matchData.LeagueGame is not null)
arenaData.LeagueMatch = matchData;
}
}
}
else if (action == ArenaAction.Destroy)
{
if (!_arenaDataDictionary.Remove(arena, out ArenaData? arenaData))
return;
try
{
if (!string.IsNullOrWhiteSpace(arenaData.ReplayRecordingFilePath))
{
StopRecordingReplay(arena, arenaData);
}
// Unregister advisors and interfaces
if (!arena.UnregisterAdvisor(ref arenaData.IFreqManagerEnforcerAdvisorToken))
return;
if (arena.UnregisterInterface(ref arenaData.ILeagueHelpToken) != 0)
return;
// Unregister callbacks.
KillCallback.Unregister(arena, Callback_Kill);
PreShipFreqChangeCallback.Unregister(arena, Callback_PreShipFreqChange);
ShipFreqChangeCallback.Unregister(arena, Callback_ShipFreqChange);
PlayerPositionPacketCallback.Unregister(arena, Callback_PlayerPositionPacket);
BricksPlacedCallback.Unregister(arena, Callback_BricksPlaced);
SpawnCallback.Unregister(arena, Callback_Spawn);
// Unregister commands.
_commandManager.RemoveCommand(CommandNames.RequestSub, Command_requestsub, arena);
_commandManager.RemoveCommand(CommandNames.Sub, Command_sub, arena);
_commandManager.RemoveCommand(CommandNames.CancelSub, Command_cancelsub, arena);
_commandManager.RemoveCommand(CommandNames.Return, Command_return, arena);
//_commandManager.RemoveCommand(CommandNames.Restart, Command_restart, arena);
//_commandManager.RemoveCommand(CommandNames.Randomize, Command_randomize, arena);
//_commandManager.RemoveCommand(CommandNames.End, Command_end, arena);
//_commandManager.RemoveCommand(CommandNames.Draw, Command_draw, arena);
_commandManager.RemoveCommand(CommandNames.ShipChange, Command_sc, arena);
_commandManager.RemoveCommand(CommandNames.Items, Command_items, arena);
_commandManager.RemoveCommand(CommandNames.MatchInfo, Command_matchinfo, arena);
_commandManager.RemoveCommand(CommandNames.FreqInfo, Command_matchinfo, arena);
_commandManager.RemoveCommand(CommandNames.Rosters, Command_rosters, arena);
_commandManager.RemoveCommand(CommandNames.Cap, Command_cap, arena);
_commandManager.RemoveCommand(CommandNames.Ready, Command_ready, arena);
_commandManager.RemoveCommand(CommandNames.Rdy, Command_ready, arena);
_commandManager.RemoveCommand(CommandNames.ForceStart, Command_forcestart, arena);
_commandManager.RemoveCommand(CommandNames.AllowPlay, Command_allowplay, arena);
_commandManager.RemoveCommand(CommandNames.AllowSub, Command_allowsub, arena);
_commandManager.RemoveCommand(CommandNames.FullSub, Command_fullsub, arena);
}
finally
{
_arenaDataPool.Return(arenaData);
}
// Clear arena for associated matches.
foreach (MatchData matchData in _matchDataDictionary.Values)
{
if (matchData.Arena == arena)
{
matchData.Arena = null;
}
}
}
}
private void Callback_PlayerAction(Player player, PlayerAction action, Arena? arena)
{
if (!player.TryGetExtraData(_pdKey, out PlayerData? playerData))
return;
if (action == PlayerAction.Connect)
{
// This flag tells us that the player just connected.
// We'll use it when the player enters the game.
playerData.IsInitialConnect = true;
}
else if (action == PlayerAction.EnterArena)
{
playerData.IsInMatchArena = playerData.AssignedSlot is not null && playerData.AssignedSlot.MatchData.Arena == arena;
if (arena is null || !_arenaDataDictionary.TryGetValue(arena, out ArenaData? arenaData))
return;
MatchData? leagueMatch = arenaData.LeagueMatch;
if (leagueMatch is not null && leagueMatch.LeagueGame is not null)
{
StringBuilder sb = _objectPoolManager.StringBuilderPool.Get();
try
{
AppendLeagueMatchInfo(sb, leagueMatch);
_chat.SendMessage(player, sb);
}
finally
{
_objectPoolManager.StringBuilderPool.Return(sb);
}
if (leagueMatch.TryGetLeagueTeam(player.Name, out Team? team))
{
_game.SetFreq(player, team.Freq);
}
}
}
else if (action == PlayerAction.EnterGame)
{
if (playerData.IsInitialConnect)
{
// The player connected and entered an arena.
playerData.IsInitialConnect = false;
if (_playerSlotDictionary.TryGetValue(player.Name!, out PlayerSlot? playerSlot))
{
// The player is associated with an ongoing match.
if (string.Equals(playerSlot.PlayerName, player.Name, StringComparison.OrdinalIgnoreCase))
{
// The player is still assigned to the slot.
playerData.AssignedSlot = playerSlot;
playerSlot.Player = player;
}
if (!string.Equals(arena!.Name, playerSlot.MatchData.ArenaName, StringComparison.OrdinalIgnoreCase))
{
// The arena the player entered is not the arena their match is in. Send them to the proper arena.
_chat.SendMessage(player, "Sending you to your ongoing match's arena. Please stand by...");
_arenaManager.SendToArena(player, playerSlot.MatchData.ArenaName, 0, 0);
return;
}
}
}
playerData.HasFullyEnteredArena = true;
PlayerSlot? slot = playerData.AssignedSlot;
if (slot is not null)
{
MatchData matchData = slot.MatchData;
if (IsStartingPhase(matchData.Status) && arena == matchData.Arena)
{
// The player entered the designated arena for a match they're in that's starting up.
ProcessMatchStateChange(slot.MatchData);
}
else if (playerData.IsReturning
&& string.Equals(arena!.Name, matchData.ArenaName, StringComparison.OrdinalIgnoreCase))
{
// The player re-entered an arena for a match they're trying to ?return to.
playerData.IsReturning = false;
ReturnToMatch(player, playerData);
}
else if (CanReturnToMatch(player, playerData, false))
{
_chat.SendMessage(player, $"Use ?{CommandNames.Return} to return to you match.");
}
}