-
-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathGameLoadingLobbyBase.cs
More file actions
527 lines (406 loc) · 20.4 KB
/
GameLoadingLobbyBase.cs
File metadata and controls
527 lines (406 loc) · 20.4 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
using ClientCore;
using ClientCore.Statistics;
using ClientGUI;
using DTAClient.Domain;
using DTAClient.Domain.Multiplayer;
using ClientCore.Extensions;
using Microsoft.Xna.Framework;
using Rampastring.Tools;
using Rampastring.XNAUI;
using Rampastring.XNAUI.XNAControls;
using System;
using System.Collections.Generic;
using System.IO;
namespace DTAClient.DXGUI.Multiplayer
{
/// <summary>
/// An abstract base class for a multiplayer game loading lobby.
/// </summary>
public abstract class GameLoadingLobbyBase : XNAWindow, ISwitchable
{
public GameLoadingLobbyBase(WindowManager windowManager, DiscordHandler discordHandler) : base(windowManager)
{
this.discordHandler = discordHandler;
}
public event EventHandler GameLeft;
/// <summary>
/// The list of players in the current saved game.
/// </summary>
protected List<SavedGamePlayer> SGPlayers = new List<SavedGamePlayer>();
/// <summary>
/// The list of players in the game lobby.
/// </summary>
protected List<PlayerInfo> Players = new List<PlayerInfo>();
protected bool IsHost = false;
protected DiscordHandler discordHandler;
protected XNAClientDropDown ddSavedGame;
protected ChatListBox lbChatMessages;
protected XNATextBox tbChatInput;
protected EnhancedSoundEffect sndGetReadySound;
protected EnhancedSoundEffect sndJoinSound;
protected EnhancedSoundEffect sndLeaveSound;
protected EnhancedSoundEffect sndMessageSound;
protected XNALabel lblDescription;
protected XNAPanel panelPlayers;
protected XNALabel[] lblPlayerNames;
private XNALabel lblMapName;
protected XNALabel lblMapNameValue;
private XNALabel lblGameMode;
protected XNALabel lblGameModeValue;
private XNALabel lblSavedGameTime;
protected XNAClientButton btnLoadGame;
protected XNAClientButton btnLeaveGame;
private List<MultiplayerColor> MPColors = new List<MultiplayerColor>();
private string loadedGameID;
private bool isSettingUp = false;
private FileSystemWatcher fsw;
private int uniqueGameId = 0;
private DateTime gameLoadTime;
public override void Initialize()
{
Name = "GameLoadingLobby";
ClientRectangle = new Rectangle(0, 0, 590, 510);
BackgroundTexture = AssetLoader.LoadTexture("loadmpsavebg.png");
lblDescription = new XNALabel(WindowManager);
lblDescription.Name = nameof(lblDescription);
lblDescription.ClientRectangle = new Rectangle(12, 12, 0, 0);
lblDescription.Text = "Wait for all players to join and get ready, then click Load Game to load the saved multiplayer game.".L10N("Client:Main:LobbyInitialTip");
panelPlayers = new XNAPanel(WindowManager);
panelPlayers.ClientRectangle = new Rectangle(12, 32, 373, 125);
panelPlayers.BackgroundTexture = AssetLoader.CreateTexture(new Color(0, 0, 0, 128), 1, 1);
panelPlayers.PanelBackgroundDrawMode = PanelBackgroundImageDrawMode.STRETCHED;
AddChild(lblDescription);
AddChild(panelPlayers);
lblPlayerNames = new XNALabel[8];
for (int i = 0; i < 8; i++)
{
XNALabel lblPlayerName = new XNALabel(WindowManager);
lblPlayerName.Name = nameof(lblPlayerName) + i;
if (i < 4)
lblPlayerName.ClientRectangle = new Rectangle(9, 9 + 30 * i, 0, 0);
else
lblPlayerName.ClientRectangle = new Rectangle(190, 9 + 30 * (i - 4), 0, 0);
lblPlayerName.Text = string.Format("Player {0}".L10N("Client:Main:PlayerX"), i) + " ";
panelPlayers.AddChild(lblPlayerName);
lblPlayerNames[i] = lblPlayerName;
}
lblMapName = new XNALabel(WindowManager);
lblMapName.Name = nameof(lblMapName);
lblMapName.FontIndex = 1;
lblMapName.ClientRectangle = new Rectangle(panelPlayers.Right + 12,
panelPlayers.Y, 0, 0);
lblMapName.Text = "MAP:".L10N("Client:Main:MapLabel");
lblMapNameValue = new XNALabel(WindowManager);
lblMapNameValue.Name = nameof(lblMapNameValue);
lblMapNameValue.ClientRectangle = new Rectangle(lblMapName.X,
lblMapName.Y + 18, 0, 0);
lblMapNameValue.Text = "Map name".L10N("Client:Main:MapName");
lblGameMode = new XNALabel(WindowManager);
lblGameMode.Name = nameof(lblGameMode);
lblGameMode.ClientRectangle = new Rectangle(lblMapName.X,
panelPlayers.Y + 40, 0, 0);
lblGameMode.FontIndex = 1;
lblGameMode.Text = "GAME MODE:".L10N("Client:Main:GameMode");
lblGameModeValue = new XNALabel(WindowManager);
lblGameModeValue.Name = nameof(lblGameModeValue);
lblGameModeValue.ClientRectangle = new Rectangle(lblGameMode.X,
lblGameMode.Y + 18, 0, 0);
lblGameModeValue.Text = "Game mode".L10N("Client:Main:GameModeValueText");
lblSavedGameTime = new XNALabel(WindowManager);
lblSavedGameTime.Name = nameof(lblSavedGameTime);
lblSavedGameTime.ClientRectangle = new Rectangle(lblMapName.X,
panelPlayers.Bottom - 40, 0, 0);
lblSavedGameTime.FontIndex = 1;
lblSavedGameTime.Text = "SAVED GAME:".L10N("Client:Main:SavedGame");
ddSavedGame = new XNAClientDropDown(WindowManager);
ddSavedGame.Name = nameof(ddSavedGame);
ddSavedGame.ClientRectangle = new Rectangle(lblSavedGameTime.X,
panelPlayers.Bottom - 21,
Width - lblSavedGameTime.X - 12, 21);
ddSavedGame.SelectedIndexChanged += DdSavedGame_SelectedIndexChanged;
lbChatMessages = new ChatListBox(WindowManager);
lbChatMessages.Name = nameof(lbChatMessages);
lbChatMessages.BackgroundTexture = AssetLoader.CreateTexture(new Color(0, 0, 0, 128), 1, 1);
lbChatMessages.PanelBackgroundDrawMode = PanelBackgroundImageDrawMode.STRETCHED;
lbChatMessages.ClientRectangle = new Rectangle(12, panelPlayers.Bottom + 12,
Width - 24,
Height - panelPlayers.Bottom - 12 - 29 - 34);
tbChatInput = new XNATextBox(WindowManager);
tbChatInput.Name = nameof(tbChatInput);
tbChatInput.ClientRectangle = new Rectangle(lbChatMessages.X,
lbChatMessages.Bottom + 3, lbChatMessages.Width, 19);
tbChatInput.MaximumTextLength = 200;
tbChatInput.EnterPressed += TbChatInput_EnterPressed;
btnLoadGame = new XNAClientButton(WindowManager);
btnLoadGame.Name = nameof(btnLoadGame);
btnLoadGame.ClientRectangle = new Rectangle(lbChatMessages.X,
tbChatInput.Bottom + 6, UIDesignConstants.BUTTON_WIDTH_133, UIDesignConstants.BUTTON_HEIGHT);
btnLoadGame.Text = "Load Game".L10N("Client:Main:LoadGame");
btnLoadGame.LeftClick += BtnLoadGame_LeftClick;
btnLeaveGame = new XNAClientButton(WindowManager);
btnLeaveGame.Name = nameof(btnLeaveGame);
btnLeaveGame.ClientRectangle = new Rectangle(Width - 145,
btnLoadGame.Y, UIDesignConstants.BUTTON_WIDTH_133, UIDesignConstants.BUTTON_HEIGHT);
btnLeaveGame.Text = "Leave Game".L10N("Client:Main:LeaveGame");
btnLeaveGame.LeftClick += BtnLeaveGame_LeftClick;
AddChild(lblMapName);
AddChild(lblMapNameValue);
AddChild(lblGameMode);
AddChild(lblGameModeValue);
AddChild(lblSavedGameTime);
AddChild(lbChatMessages);
AddChild(tbChatInput);
AddChild(btnLoadGame);
AddChild(btnLeaveGame);
AddChild(ddSavedGame);
base.Initialize();
sndJoinSound = new EnhancedSoundEffect("joingame.wav", 0.0, 0.0, ClientConfiguration.Instance.SoundGameLobbyJoinCooldown);
sndLeaveSound = new EnhancedSoundEffect("leavegame.wav", 0.0, 0.0, ClientConfiguration.Instance.SoundGameLobbyLeaveCooldown);
sndMessageSound = new EnhancedSoundEffect("message.wav", 0.0, 0.0, ClientConfiguration.Instance.SoundMessageCooldown);
sndGetReadySound = new EnhancedSoundEffect("getready.wav", 0.0, 0.0, ClientConfiguration.Instance.SoundGameLobbyGetReadyCooldown);
MPColors = MultiplayerColor.LoadColors();
WindowManager.CenterControlOnScreen(this);
if (SavedGameManager.AreSavedGamesAvailable())
{
fsw = new FileSystemWatcher(SafePath.CombineDirectoryPath(ProgramConstants.GamePath, "Saved Games"), "*.NET");
fsw.EnableRaisingEvents = false;
fsw.Created += fsw_Created;
fsw.Changed += fsw_Created;
}
}
/// <summary>
/// Updates Discord Rich Presence with actual information.
/// </summary>
/// <param name="resetTimer">Whether to restart the "Elapsed" timer or not</param>
protected abstract void UpdateDiscordPresence(bool resetTimer = false);
/// <summary>
/// Resets Discord Rich Presence to default state.
/// </summary>
protected void ResetDiscordPresence() => discordHandler.UpdatePresence();
private void BtnLeaveGame_LeftClick(object sender, EventArgs e) => LeaveGame();
protected virtual void LeaveGame()
{
GameLeft?.Invoke(this, EventArgs.Empty);
ResetDiscordPresence();
}
private void fsw_Created(object sender, FileSystemEventArgs e) =>
AddCallback(new Action<FileSystemEventArgs>(HandleFSWEvent), e);
private void HandleFSWEvent(FileSystemEventArgs e)
{
Logger.Log("FSW Event: " + e.FullPath);
if (Path.GetFileName(e.FullPath) == "SAVEGAME.NET")
{
SavedGameManager.RenameSavedGame();
}
}
private void BtnLoadGame_LeftClick(object sender, EventArgs e)
{
if (!IsHost)
{
RequestReadyStatus();
return;
}
if (Players.Find(p => !p.Ready) != null)
{
GetReadyNotification();
return;
}
HostStartGame();
}
protected abstract void RequestReadyStatus();
protected virtual void GetReadyNotification()
{
AddNotice("The game host wants to load the game but cannot because not all players are ready!".L10N("Client:Main:GetReadyPlease"));
if (!IsHost && !Players.Find(p => p.Name == ProgramConstants.PLAYERNAME).Ready)
sndGetReadySound.Play();
#if WINFORMS
WindowManager.FlashWindow();
#endif
}
protected virtual void NotAllPresentNotification() =>
AddNotice("You cannot load the game before all players are present.".L10N("Client:Main:NotAllPresent"));
protected abstract void HostStartGame();
protected void LoadGame()
{
FileInfo spawnFileInfo = SafePath.GetFile(ProgramConstants.GamePath, "spawn.ini");
spawnFileInfo.Delete();
File.Copy(SafePath.CombineFilePath(ProgramConstants.GamePath, "Saved Games", "spawnSG.ini"), spawnFileInfo.FullName);
IniFile spawnIni = new IniFile(spawnFileInfo.FullName);
int sgIndex = (ddSavedGame.Items.Count - 1) - ddSavedGame.SelectedIndex;
spawnIni.SetStringValue("Settings", "SaveGameName",
string.Format("SVGM_{0}.NET", sgIndex.ToString("D3")));
spawnIni.SetBooleanValue("Settings", "LoadSaveGame", true);
PlayerInfo localPlayer = Players.Find(p => p.Name == ProgramConstants.PLAYERNAME);
if (localPlayer == null)
return;
spawnIni.SetIntValue("Settings", "Port", localPlayer.Port);
spawnIni.SetIntValue("Settings", "PlayerCount", SGPlayers.Count);
for (int i = 1; i < SGPlayers.Count; i++)
{
string otherSectionName = $"Other{i}";
string otherName = spawnIni.GetStringValue(otherSectionName, "Name", string.Empty);
if (string.IsNullOrEmpty(otherName))
continue;
PlayerInfo otherPlayer = Players.Find(p => p.Name == otherName);
if (otherPlayer == null)
{
spawnIni.RemoveSection(otherSectionName); // don't connect to missing players
}
else
{
spawnIni.SetStringValue(otherSectionName, "Ip", otherPlayer.IPAddress);
spawnIni.SetIntValue(otherSectionName, "Port", otherPlayer.Port);
}
}
WriteSpawnIniAdditions(spawnIni);
spawnIni.WriteIniFile();
FileInfo spawnMapFileInfo = SafePath.GetFile(ProgramConstants.GamePath, "spawnmap.ini");
spawnMapFileInfo.Delete();
using (var spawnMapStreamWriter = new StreamWriter(spawnMapFileInfo.FullName))
{
spawnMapStreamWriter.WriteLine("[Map]");
spawnMapStreamWriter.WriteLine("Size=0,0,50,50");
spawnMapStreamWriter.WriteLine("LocalSize=0,0,50,50");
spawnMapStreamWriter.WriteLine();
}
gameLoadTime = DateTime.Now;
GameProcessLogic.GameProcessExited += SharedUILogic_GameProcessExited;
GameProcessLogic.StartGameProcess(WindowManager);
fsw.EnableRaisingEvents = true;
UpdateDiscordPresence(true);
}
private void SharedUILogic_GameProcessExited() =>
AddCallback(new Action(HandleGameProcessExited), null);
protected virtual void HandleGameProcessExited()
{
fsw.EnableRaisingEvents = false;
GameProcessLogic.GameProcessExited -= SharedUILogic_GameProcessExited;
var matchStatistics = StatisticsManager.Instance.GetMatchWithGameID(uniqueGameId);
if (matchStatistics != null)
{
int oldLength = matchStatistics.LengthInSeconds;
int newLength = matchStatistics.LengthInSeconds +
(int)(DateTime.Now - gameLoadTime).TotalSeconds;
matchStatistics.ParseStatistics(ProgramConstants.GamePath,
ClientConfiguration.Instance.LocalGame, true);
matchStatistics.LengthInSeconds = newLength;
StatisticsManager.Instance.SaveDatabase();
}
UpdateDiscordPresence(true);
}
protected virtual void WriteSpawnIniAdditions(IniFile spawnIni)
{
// Do nothing by default
}
protected void AddNotice(string notice) => AddNotice(notice, Color.White);
protected abstract void AddNotice(string message, Color color);
/// <summary>
/// Refreshes the UI based on the latest saved game
/// and information in the saved spawn.ini file, as well
/// as information on whether the local player is the host of the game.
/// </summary>
public virtual void Refresh(bool isHost)
{
isSettingUp = true;
IsHost = isHost;
SGPlayers.Clear();
Players.Clear();
ddSavedGame.Items.Clear();
lbChatMessages.Clear();
lbChatMessages.TopIndex = 0;
ddSavedGame.AllowDropDown = isHost;
btnLoadGame.Text = isHost ? "Load Game".L10N("Client:Main:ButtonLoadGame") : "I'm Ready".L10N("Client:Main:ButtonGetReady");
IniFile spawnSGIni = new IniFile(SafePath.CombineFilePath(ProgramConstants.GamePath, "Saved Games", "spawnSG.ini"));
loadedGameID = spawnSGIni.GetStringValue("Settings", "GameID", "0");
lblMapNameValue.Tag = spawnSGIni.GetStringValue("Settings", "UIMapName", string.Empty);
lblMapNameValue.Text = ((string)lblGameModeValue.Tag).L10N($"INI:Maps:{spawnSGIni.GetStringValue("Settings", "MapID", string.Empty)}:Description");
lblGameModeValue.Tag = spawnSGIni.GetStringValue("Settings", "UIGameMode", string.Empty);
lblGameModeValue.Text = ((string)lblGameModeValue.Tag).L10N($"INI:GameModes:{(string)lblGameModeValue.Tag}:UIName");
uniqueGameId = spawnSGIni.GetIntValue("Settings", "GameID", -1);
int playerCount = spawnSGIni.GetIntValue("Settings", "PlayerCount", 0);
SavedGamePlayer localPlayer = new SavedGamePlayer();
localPlayer.Name = ProgramConstants.PLAYERNAME;
localPlayer.ColorIndex = MPColors.FindIndex(
c => c.GameColorIndex == spawnSGIni.GetIntValue("Settings", "Color", 0));
SGPlayers.Add(localPlayer);
for (int i = 1; i < playerCount; i++)
{
string sectionName = "Other" + i;
SavedGamePlayer sgPlayer = new SavedGamePlayer();
sgPlayer.Name = spawnSGIni.GetStringValue(sectionName, "Name", "Unknown player".L10N("Client:Main:UnknownPlayer"));
sgPlayer.ColorIndex = MPColors.FindIndex(
c => c.GameColorIndex == spawnSGIni.GetIntValue(sectionName, "Color", 0));
SGPlayers.Add(sgPlayer);
}
for (int i = 0; i < SGPlayers.Count; i++)
{
lblPlayerNames[i].Enabled = true;
lblPlayerNames[i].Visible = true;
}
for (int i = SGPlayers.Count; i < 8; i++)
{
lblPlayerNames[i].Enabled = false;
lblPlayerNames[i].Visible = false;
}
List<string> timestamps = SavedGameManager.GetSaveGameTimestamps();
timestamps.Reverse(); // Most recent saved game first
timestamps.ForEach(ts => ddSavedGame.AddItem(ts));
if (ddSavedGame.Items.Count > 0)
ddSavedGame.SelectedIndex = 0;
CopyPlayerDataToUI();
isSettingUp = false;
}
protected void CopyPlayerDataToUI()
{
for (int i = 0; i < SGPlayers.Count; i++)
{
SavedGamePlayer sgPlayer = SGPlayers[i];
PlayerInfo pInfo = Players.Find(p => p.Name == SGPlayers[i].Name);
XNALabel playerLabel = lblPlayerNames[i];
if (pInfo == null)
{
playerLabel.RemapColor = Color.Gray;
playerLabel.Text = sgPlayer.Name + " " + "(Not present)".L10N("Client:Main:NotPresentSuffix");
continue;
}
playerLabel.RemapColor = sgPlayer.ColorIndex > -1 ? MPColors[sgPlayer.ColorIndex].XnaColor
: Color.White;
playerLabel.Text = pInfo.Ready ? sgPlayer.Name : sgPlayer.Name + " " + "(Not Ready)".L10N("Client:Main:NotReadySuffix");
}
}
protected virtual string GetIPAddressForPlayer(PlayerInfo pInfo) => "0.0.0.0";
private void DdSavedGame_SelectedIndexChanged(object sender, EventArgs e)
{
if (!IsHost)
return;
for (int i = 1; i < Players.Count; i++)
Players[i].Ready = false;
CopyPlayerDataToUI();
if (!isSettingUp)
BroadcastOptions();
UpdateDiscordPresence();
}
private void TbChatInput_EnterPressed(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(tbChatInput.Text))
return;
SendChatMessage(tbChatInput.Text);
tbChatInput.Text = string.Empty;
}
/// <summary>
/// Override in a derived class to broadcast player ready statuses and the selected
/// saved game to players.
/// </summary>
protected abstract void BroadcastOptions();
protected abstract void SendChatMessage(string message);
public override void Draw(GameTime gameTime)
{
Renderer.FillRectangle(new Rectangle(0, 0, WindowManager.RenderResolutionX, WindowManager.RenderResolutionY),
new Color(0, 0, 0, 255));
base.Draw(gameTime);
}
public void SwitchOn() => Enable();
public void SwitchOff() => Disable();
public abstract string GetSwitchName();
}
}