misc: fmt

This commit is contained in:
2026-04-15 17:25:16 -04:00
Unverified
parent 5b4cd944c1
commit bcde443c65
8 changed files with 665 additions and 670 deletions

View File

@@ -3,4 +3,4 @@ using System;
public partial class AddressUI : TextEdit {
public override void _Ready() { Text = Connection.WS_DEFAULT_ADDRESS; }
}
}

View File

@@ -8,126 +8,126 @@ public partial class AdminControls : HBoxContainer {
[Export] public Slider Timeout;
public override void _Ready() {
Connection.Instance.OnBecomeAdmin += UpdateUI;
Connection.Instance.OnTournamentEnd += UpdateUI;
Connection.Instance.OnStartTournament += UpdateUI;
Connection.Instance.OnCancelTournamentAck += UpdateUI;
Connection.Instance.OnGetDataAcks += UpdateUI;
Connection.Instance.OnSetDataAcks += UpdateUI;
Connection.Instance.OnBecomeAdmin += UpdateUI;
Connection.Instance.OnTournamentEnd += UpdateUI;
Connection.Instance.OnStartTournament += UpdateUI;
Connection.Instance.OnCancelTournamentAck += UpdateUI;
Connection.Instance.OnGetDataAcks += UpdateUI;
Connection.Instance.OnSetDataAcks += UpdateUI;
StartTournament.Pressed += () => Connection.Instance.StartTournament();
CancelTournament.Pressed += () => Connection.Instance.CancelTournament();
StartTournament.Pressed += () => Connection.Instance.StartTournament();
CancelTournament.Pressed += () => Connection.Instance.CancelTournament();
UpdateUI();
UpdateUI();
Timeout.ValueChanged += value =>
{
Connection.Instance.SetMoveWait((float)value);
var time = Connection.Instance.CurrentWaitTimeout.ToString();
if (time.Length > 3) {
time = time.Substring(0, 3);
}
Label.Text = "Wait To Move: " + time + "s ";
};
Timeout.ValueChanged += value =>
{
Connection.Instance.SetMoveWait((float)value);
var time = Connection.Instance.CurrentWaitTimeout.ToString();
if (time.Length > 3) {
time = time.Substring(0, 3);
}
Label.Text = "Wait To Move: " + time + "s ";
};
BecomeAdmin.Pressed += showAuthPopup;
BecomeAdmin.Pressed += showAuthPopup;
}
public override void _ExitTree() {
Connection.Instance.OnBecomeAdmin -= UpdateUI;
Connection.Instance.OnTournamentEnd -= UpdateUI;
Connection.Instance.OnStartTournament -= UpdateUI;
Connection.Instance.OnCancelTournamentAck -= UpdateUI;
Connection.Instance.OnGetDataAcks -= UpdateUI;
Connection.Instance.OnSetDataAcks -= UpdateUI;
Connection.Instance.OnBecomeAdmin -= UpdateUI;
Connection.Instance.OnTournamentEnd -= UpdateUI;
Connection.Instance.OnStartTournament -= UpdateUI;
Connection.Instance.OnCancelTournamentAck -= UpdateUI;
Connection.Instance.OnGetDataAcks -= UpdateUI;
Connection.Instance.OnSetDataAcks -= UpdateUI;
}
private void UpdateUI() {
if (!Connection.Instance.IsAdmin) {
BecomeAdmin.Show();
StartTournament.Hide();
CancelTournament.Hide();
Label.Hide();
Timeout.Hide();
} else {
BecomeAdmin.Hide();
Label.Show();
Timeout.Show();
}
if (!Connection.Instance.IsAdmin) {
BecomeAdmin.Show();
StartTournament.Hide();
CancelTournament.Hide();
Label.Hide();
Timeout.Hide();
} else {
BecomeAdmin.Hide();
Label.Show();
Timeout.Show();
}
if (Connection.Instance.IsAdmin && Connection.Instance.DemoMode) {
StartTournament.Hide();
CancelTournament.Hide();
} else if (Connection.Instance.IsAdmin && Connection.Instance.ActiveTournament != TournamentType.None) {
StartTournament.Hide();
CancelTournament.Show();
} else if (Connection.Instance.IsAdmin) {
StartTournament.Show();
CancelTournament.Hide();
}
if (Connection.Instance.IsAdmin && Connection.Instance.DemoMode) {
StartTournament.Hide();
CancelTournament.Hide();
} else if (Connection.Instance.IsAdmin && Connection.Instance.ActiveTournament != TournamentType.None) {
StartTournament.Hide();
CancelTournament.Show();
} else if (Connection.Instance.IsAdmin) {
StartTournament.Show();
CancelTournament.Hide();
}
Timeout.Value = Connection.Instance.CurrentWaitTimeout;
var time = Connection.Instance.CurrentWaitTimeout.ToString();
if (time.Length > 3) {
time = time.Substring(0, 3);
}
Timeout.Value = Connection.Instance.CurrentWaitTimeout;
var time = Connection.Instance.CurrentWaitTimeout.ToString();
if (time.Length > 3) {
time = time.Substring(0, 3);
}
Label.Text = "Wait To Move: " + time + "s ";
Label.Text = "Wait To Move: " + time + "s ";
}
private void showAuthPopup() {
var authWindow = new Window();
authWindow.Theme = GD.Load<Theme>("res://assets/theme.tres");
authWindow.AlwaysOnTop = true;
authWindow.MaximizeDisabled = true;
authWindow.Unresizable = true;
authWindow.InitialPosition = Window.WindowInitialPosition.CenterMainWindowScreen;
authWindow.Size = new Vector2I(256, 128);
authWindow.CloseRequested += () =>
{
GetTree().Root.CallDeferred(Node.MethodName.RemoveChild, authWindow);
};
var authWindow = new Window();
authWindow.Theme = GD.Load<Theme>("res://assets/theme.tres");
authWindow.AlwaysOnTop = true;
authWindow.MaximizeDisabled = true;
authWindow.Unresizable = true;
authWindow.InitialPosition = Window.WindowInitialPosition.CenterMainWindowScreen;
authWindow.Size = new Vector2I(256, 128);
authWindow.CloseRequested += () =>
{
GetTree().Root.CallDeferred(Node.MethodName.RemoveChild, authWindow);
};
var vbox = new VBoxContainer();
vbox.LayoutMode = 1;
vbox.AnchorBottom = 1.0f;
vbox.AnchorRight = 1.0f;
vbox.GrowHorizontal = GrowDirection.Both;
vbox.GrowVertical = GrowDirection.Both;
vbox.Alignment = AlignmentMode.Center;
var vbox = new VBoxContainer();
vbox.LayoutMode = 1;
vbox.AnchorBottom = 1.0f;
vbox.AnchorRight = 1.0f;
vbox.GrowHorizontal = GrowDirection.Both;
vbox.GrowVertical = GrowDirection.Both;
vbox.Alignment = AlignmentMode.Center;
var passwordBox = new TextEdit();
passwordBox.PlaceholderText = "Password";
passwordBox.SetCustomMinimumSize(new Vector2(32, 32));
var passwordBox = new TextEdit();
passwordBox.PlaceholderText = "Password";
passwordBox.SetCustomMinimumSize(new Vector2(32, 32));
passwordBox.GuiInput += e =>
{
if (passwordBox.HasFocus() && e is InputEventKey inputEventKey && inputEventKey.IsPressed()) {
if (inputEventKey.KeyLabel == Key.Enter) {
Connection.Instance.AdminAuth(passwordBox.Text);
GetTree().Root.CallDeferred(Node.MethodName.RemoveChild, authWindow);
GetViewport().SetInputAsHandled();
}
passwordBox.GuiInput += e =>
{
if (passwordBox.HasFocus() && e is InputEventKey inputEventKey && inputEventKey.IsPressed()) {
if (inputEventKey.KeyLabel == Key.Enter) {
Connection.Instance.AdminAuth(passwordBox.Text);
GetTree().Root.CallDeferred(Node.MethodName.RemoveChild, authWindow);
GetViewport().SetInputAsHandled();
}
if (inputEventKey.KeyLabel == Key.Space) {
GetViewport().SetInputAsHandled();
}
}
};
if (inputEventKey.KeyLabel == Key.Space) {
GetViewport().SetInputAsHandled();
}
}
};
var button = new Button();
button.Text = "Login";
button.Pressed += () =>
{
Connection.Instance.AdminAuth(passwordBox.Text);
GetTree().Root.CallDeferred(Node.MethodName.RemoveChild, authWindow);
};
var button = new Button();
button.Text = "Login";
button.Pressed += () =>
{
Connection.Instance.AdminAuth(passwordBox.Text);
GetTree().Root.CallDeferred(Node.MethodName.RemoveChild, authWindow);
};
vbox.AddChild(passwordBox);
vbox.AddChild(button);
vbox.AddChild(passwordBox);
vbox.AddChild(button);
authWindow.AddChild(vbox);
authWindow.AddChild(vbox);
GetTree().Root.AddChild(authWindow);
GetTree().Root.AddChild(authWindow);
}
}
}

View File

@@ -5,9 +5,9 @@ public partial class BackButton : TextureButton {
private const string BRACKET_SCENE_PATH = "res://scenes/bracket_view.tscn";
public override void _Pressed() {
transitionToBracket();
base._Pressed();
transitionToBracket();
base._Pressed();
}
private void transitionToBracket() { GetTree().ChangeSceneToFile(BRACKET_SCENE_PATH); }
}
}

View File

@@ -33,131 +33,131 @@ public partial class BoardScreen : Node2D {
// Called when the node enters the scene tree for the first time.
public override void _Ready() {
// Node initialization
player1Card = GetNode<Node2D>("Player1Card");
player2Card = GetNode<Node2D>("Player2Card");
// Node initialization
player1Card = GetNode<Node2D>("Player1Card");
player2Card = GetNode<Node2D>("Player2Card");
player1Card.GetNode<Label>("Name").Resized += () =>
setPlayerCardScale((player1Card.GetNode<Label>("Name").GetRect().Size.X + 7) / 16, player1Card);
player2Card.GetNode<Label>("Name").Resized += () =>
setPlayerCardScale((player2Card.GetNode<Label>("Name").GetRect().Size.X + 7) / 16, player2Card);
player1Card.GetNode<Label>("Name").Resized += () =>
setPlayerCardScale((player1Card.GetNode<Label>("Name").GetRect().Size.X + 7) / 16, player1Card);
player2Card.GetNode<Label>("Name").Resized += () =>
setPlayerCardScale((player2Card.GetNode<Label>("Name").GetRect().Size.X + 7) / 16, player2Card);
redChip = GD.Load<PackedScene>(RED_CHIP_PATH);
ylwChip = GD.Load<PackedScene>(YELLOW_CHIP_PATH);
redChip = GD.Load<PackedScene>(RED_CHIP_PATH);
ylwChip = GD.Load<PackedScene>(YELLOW_CHIP_PATH);
matchData = Connection.Instance.CurrentObservingMatch;
player1Card.GetNode<Label>("Name").Text = matchData.player1;
player2Card.GetNode<Label>("Name").Text = matchData.player2;
matchData = Connection.Instance.CurrentObservingMatch;
player1Card.GetNode<Label>("Name").Text = matchData.player1;
player2Card.GetNode<Label>("Name").Text = matchData.player2;
if (Connection.Instance.PreviousMoves.Count == 0) {
player1Card.GetNode<Label>("Status").Show();
player2Card.GetNode<Label>("Status").Hide();
} else if (Connection.Instance.PreviousMoves.Last().Item1 == matchData.player1) {
player1Card.GetNode<Label>("Status").Hide();
player2Card.GetNode<Label>("Status").Show();
} else {
player1Card.GetNode<Label>("Status").Show();
player2Card.GetNode<Label>("Status").Hide();
}
if (Connection.Instance.PreviousMoves.Count == 0) {
player1Card.GetNode<Label>("Status").Show();
player2Card.GetNode<Label>("Status").Hide();
} else if (Connection.Instance.PreviousMoves.Last().Item1 == matchData.player1) {
player1Card.GetNode<Label>("Status").Hide();
player2Card.GetNode<Label>("Status").Show();
} else {
player1Card.GetNode<Label>("Status").Show();
player2Card.GetNode<Label>("Status").Hide();
}
Connection.Instance.OnObserveWin += OnObserveWin;
Connection.Instance.OnObserveDraw += OnObserveDraw;
Connection.Instance.OnObserveTerminated += OnObserveTerminated;
Connection.Instance.OnObserveMove += OnObserveMove;
Connection.Instance.OnObserveWin += OnObserveWin;
Connection.Instance.OnObserveDraw += OnObserveDraw;
Connection.Instance.OnObserveTerminated += OnObserveTerminated;
Connection.Instance.OnObserveMove += OnObserveMove;
}
public override void _Process(double delta) {
if (Connection.Instance.PreviousMoves.Count != 0 && currentTimeout <= 0.0f) {
var move = Connection.Instance.PreviousMoves[0];
Connection.Instance.PreviousMoves.RemoveAt(0);
if (move.Item1 == matchData.player1) {
spawnRed(move.Item2);
} else {
spawnYellow(move.Item2);
}
if (Connection.Instance.PreviousMoves.Count != 0 && currentTimeout <= 0.0f) {
var move = Connection.Instance.PreviousMoves[0];
Connection.Instance.PreviousMoves.RemoveAt(0);
if (move.Item1 == matchData.player1) {
spawnRed(move.Item2);
} else {
spawnYellow(move.Item2);
}
currentTimeout = MOVE_TIMEOUT_BEFORE_PLACE;
} else if (currentTimeout >= 0.0f) {
currentTimeout -= delta;
}
currentTimeout = MOVE_TIMEOUT_BEFORE_PLACE;
} else if (currentTimeout >= 0.0f) {
currentTimeout -= delta;
}
if (_lastMove) {
_lastMoveTimer -= (float)delta;
}
if (_lastMove) {
_lastMoveTimer -= (float)delta;
}
if (_lastMoveTimer <= 0.0f) {
if (_winner == "") {
showPopupMessage("Draw!");
} else {
showPopupMessage(_winner + " wins!");
}
}
if (_lastMoveTimer <= 0.0f) {
if (_winner == "") {
showPopupMessage("Draw!");
} else {
showPopupMessage(_winner + " wins!");
}
}
}
public override void _ExitTree() {
Connection.Instance.OnObserveWin -= OnObserveWin;
Connection.Instance.OnObserveDraw -= OnObserveDraw;
Connection.Instance.OnObserveTerminated -= OnObserveTerminated;
Connection.Instance.OnObserveMove -= OnObserveMove;
Connection.Instance.OnObserveWin -= OnObserveWin;
Connection.Instance.OnObserveDraw -= OnObserveDraw;
Connection.Instance.OnObserveTerminated -= OnObserveTerminated;
Connection.Instance.OnObserveMove -= OnObserveMove;
}
private void OnObserveWin(string winner) {
_lastMove = true;
_winner = winner;
player1Card.GetNode<Label>("Status").Hide();
player2Card.GetNode<Label>("Status").Hide();
_lastMove = true;
_winner = winner;
player1Card.GetNode<Label>("Status").Hide();
player2Card.GetNode<Label>("Status").Hide();
}
private void OnObserveDraw() {
_lastMove = true;
player1Card.GetNode<Label>("Status").Hide();
player2Card.GetNode<Label>("Status").Hide();
_lastMove = true;
player1Card.GetNode<Label>("Status").Hide();
player2Card.GetNode<Label>("Status").Hide();
}
private void OnObserveTerminated() {
showPopupMessage("Match Terminated");
player1Card.GetNode<Label>("Status").Hide();
player2Card.GetNode<Label>("Status").Hide();
showPopupMessage("Match Terminated");
player1Card.GetNode<Label>("Status").Hide();
player2Card.GetNode<Label>("Status").Hide();
}
private void OnObserveMove(string username, int column) {
if (username == matchData.player1) {
if (!_lastMove)
player2Card.GetNode<Label>("Status").Show();
player1Card.GetNode<Label>("Status").Hide();
} else {
if (!_lastMove)
player1Card.GetNode<Label>("Status").Show();
player2Card.GetNode<Label>("Status").Hide();
}
if (username == matchData.player1) {
if (!_lastMove)
player2Card.GetNode<Label>("Status").Show();
player1Card.GetNode<Label>("Status").Hide();
} else {
if (!_lastMove)
player1Card.GetNode<Label>("Status").Show();
player2Card.GetNode<Label>("Status").Hide();
}
Connection.Instance.PreviousMoves.Add((username, column));
Connection.Instance.PreviousMoves.Add((username, column));
}
private void showPopupMessage(string message) {
var popup = new Popup();
popup.AlwaysOnTop = true;
popup.Size = new Vector2I(200, 100);
popup.Theme = GD.Load<Theme>("res://assets/theme.tres");
var text = new Label();
text.Text = message;
var sfx = new AudioStreamPlayer();
sfx.Stream = endingSfx;
sfx.VolumeDb = -2;
popup.AddChild(sfx);
popup.AddChild(text);
text.GrowHorizontal = Control.GrowDirection.Both;
text.GrowVertical = Control.GrowDirection.Both;
text.HorizontalAlignment = HorizontalAlignment.Center;
text.VerticalAlignment = VerticalAlignment.Center;
text.AnchorsPreset = (int)Control.LayoutPreset.FullRect;
popup.InitialPosition = Window.WindowInitialPosition.CenterMainWindowScreen;
popup.PopupHide += () => popup.QueueFree();
GetTree().Root.AddChild(popup);
popup.PopupCentered();
sfx.Play();
popup.Show();
transitionToBracket();
var popup = new Popup();
popup.AlwaysOnTop = true;
popup.Size = new Vector2I(200, 100);
popup.Theme = GD.Load<Theme>("res://assets/theme.tres");
var text = new Label();
text.Text = message;
var sfx = new AudioStreamPlayer();
sfx.Stream = endingSfx;
sfx.VolumeDb = -2;
popup.AddChild(sfx);
popup.AddChild(text);
text.GrowHorizontal = Control.GrowDirection.Both;
text.GrowVertical = Control.GrowDirection.Both;
text.HorizontalAlignment = HorizontalAlignment.Center;
text.VerticalAlignment = VerticalAlignment.Center;
text.AnchorsPreset = (int)Control.LayoutPreset.FullRect;
popup.InitialPosition = Window.WindowInitialPosition.CenterMainWindowScreen;
popup.PopupHide += () => popup.QueueFree();
GetTree().Root.AddChild(popup);
popup.PopupCentered();
sfx.Play();
popup.Show();
transitionToBracket();
}
private void transitionToBracket() { GetTree().ChangeSceneToFile(BRACKET_SCENE_PATH); }
@@ -169,63 +169,63 @@ public partial class BoardScreen : Node2D {
* Will return row of board in which chip can be placed
*/
private int canPlaceOnCol(int col) {
if (col < 0 || col > 6) // Col out of range
return -1;
if (col < 0 || col > 6) // Col out of range
return -1;
return getNextAvailRow(col);
return getNextAvailRow(col);
}
private int getNextAvailRow(int col) {
for (int i = chips.GetLength(0) - 1; i >= 0; i--) {
// Start at bottom
if (chips[i, col] == null)
return i;
}
for (int i = chips.GetLength(0) - 1; i >= 0; i--) {
// Start at bottom
if (chips[i, col] == null)
return i;
}
return -1;
return -1;
}
private void spawnRed(int col) {
int row = canPlaceOnCol(col);
if (row == -1) {
GD.Print("Invalid Placement!");
return;
}
int row = canPlaceOnCol(col);
if (row == -1) {
GD.Print("Invalid Placement!");
return;
}
RigidBody2D newNode = redChip.Instantiate<RigidBody2D>();
AddChild(newNode);
newNode.Position = new Vector2(CHIP_SCALE * (CHIP_X_OFF + (CHIP_SIZE + CHIP_PADDING) * col),
-(CHIP_SIZE + CHIP_PADDING) * 7);
RigidBody2D newNode = redChip.Instantiate<RigidBody2D>();
AddChild(newNode);
newNode.Position = new Vector2(CHIP_SCALE * (CHIP_X_OFF + (CHIP_SIZE + CHIP_PADDING) * col),
-(CHIP_SIZE + CHIP_PADDING) * 7);
chips[row, col] = newNode;
chips[row, col] = newNode;
}
private void spawnYellow(int col) {
int row = canPlaceOnCol(col);
if (row == -1) {
GD.Print("Invalid Placement!");
return;
}
int row = canPlaceOnCol(col);
if (row == -1) {
GD.Print("Invalid Placement!");
return;
}
RigidBody2D newNode = ylwChip.Instantiate<RigidBody2D>();
AddChild(newNode);
newNode.Position = new Vector2(CHIP_SCALE * (CHIP_X_OFF + (CHIP_SIZE + CHIP_PADDING) * col),
-(CHIP_SIZE + CHIP_PADDING) * 7);
RigidBody2D newNode = ylwChip.Instantiate<RigidBody2D>();
AddChild(newNode);
newNode.Position = new Vector2(CHIP_SCALE * (CHIP_X_OFF + (CHIP_SIZE + CHIP_PADDING) * col),
-(CHIP_SIZE + CHIP_PADDING) * 7);
chips[row, col] = newNode;
chips[row, col] = newNode;
}
private void setPlayerCardScale(float x, Node2D playerCard) {
Sprite2D cardCenter = playerCard.GetNode<Sprite2D>("Center");
Sprite2D cardRight = playerCard.GetNode<Sprite2D>("Right");
Sprite2D cardCenter = playerCard.GetNode<Sprite2D>("Center");
Sprite2D cardRight = playerCard.GetNode<Sprite2D>("Right");
float offX = 16 * x / 2;
cardCenter.Scale = new Vector2(x, 2);
cardCenter.Position = new Vector2(CARD_CENTER_X_DEFAULT + offX, cardCenter.Position.Y);
float offX = 16 * x / 2;
cardCenter.Scale = new Vector2(x, 2);
cardCenter.Position = new Vector2(CARD_CENTER_X_DEFAULT + offX, cardCenter.Position.Y);
cardRight.Position =
new Vector2(CARD_CENTER_X_DEFAULT + offX * 2 + 8,
cardRight.Position.Y); // 8 is a magic number (im too lazy) for the size of the card edge multipled by 2
cardRight.Position =
new Vector2(CARD_CENTER_X_DEFAULT + offX * 2 + 8,
cardRight.Position.Y); // 8 is a magic number (im too lazy) for the size of the card edge multipled by 2
}
}
@@ -238,4 +238,4 @@ enum Direction {
DOWN_LEFT,
LEFT,
UP_LEFT
}
}

View File

@@ -12,80 +12,80 @@ public partial class BracketScene : Control {
private List<MatchData> matchList;
public override void _Ready() {
Players.SetColumnTitle(0, "Name");
Players.SetColumnTitle(1, "Ready");
Players.SetColumnTitle(2, "Playing");
Players.HideRoot = true;
Players.ButtonClicked += kickPlayer;
Players.SetColumnTitle(0, "Name");
Players.SetColumnTitle(1, "Ready");
Players.SetColumnTitle(2, "Playing");
Players.HideRoot = true;
Players.ButtonClicked += kickPlayer;
Matches.SetColumnTitle(0, "Match");
Matches.SetColumnTitle(1, "Red");
Matches.SetColumnTitle(2, "Yellow");
Matches.HideRoot = true;
Matches.ButtonClicked += watchGame;
Matches.ButtonClicked += terminateGame;
Matches.SetColumnTitle(0, "Match");
Matches.SetColumnTitle(1, "Red");
Matches.SetColumnTitle(2, "Yellow");
Matches.HideRoot = true;
Matches.ButtonClicked += watchGame;
Matches.ButtonClicked += terminateGame;
Connection.Instance.OnUpdatedPlayers += updatePlayers;
Connection.Instance.OnUpdatedMatches += updateMatches;
Connection.Instance.OnWatchGameAck += transitionToBoard;
Connection.Instance.OnUpdatedPlayers += updatePlayers;
Connection.Instance.OnUpdatedMatches += updateMatches;
Connection.Instance.OnWatchGameAck += transitionToBoard;
}
public override void _ExitTree() {
Connection.Instance.OnUpdatedPlayers -= updatePlayers;
Connection.Instance.OnUpdatedMatches -= updateMatches;
Connection.Instance.OnWatchGameAck -= transitionToBoard;
Connection.Instance.OnUpdatedPlayers -= updatePlayers;
Connection.Instance.OnUpdatedMatches -= updateMatches;
Connection.Instance.OnWatchGameAck -= transitionToBoard;
}
private void updatePlayers(List<PlayerData> newPlayerList) {
Players.Clear();
playerList = newPlayerList;
playerList.Sort((a, b) => a.Username.CompareTo(b.Username));
var root = Players.CreateItem();
for (int i = 0; i < playerList.Count; i++) {
var item = Players.CreateItem(root);
item.SetText(0, newPlayerList[i].Username);
item.SetText(1, newPlayerList[i].IsReady ? "Yes" : "No");
item.SetText(2, newPlayerList[i].IsPlaying ? "Yes" : "No");
if (Connection.Instance.IsAdmin) {
item.AddButton(0, TerminateKickButton, i, false, "Kick");
}
}
Players.Clear();
playerList = newPlayerList;
playerList.Sort((a, b) => a.Username.CompareTo(b.Username));
var root = Players.CreateItem();
for (int i = 0; i < playerList.Count; i++) {
var item = Players.CreateItem(root);
item.SetText(0, newPlayerList[i].Username);
item.SetText(1, newPlayerList[i].IsReady ? "Yes" : "No");
item.SetText(2, newPlayerList[i].IsPlaying ? "Yes" : "No");
if (Connection.Instance.IsAdmin) {
item.AddButton(0, TerminateKickButton, i, false, "Kick");
}
}
}
private void updateMatches(List<MatchData> newMatchList) {
Matches.Clear();
matchList = newMatchList;
var root = Matches.CreateItem();
for (int i = 0; i < newMatchList.Count; i++) {
var item = Matches.CreateItem(root);
item.SetText(0, newMatchList[i].matchId.ToString());
item.SetText(1, newMatchList[i].player1);
item.SetText(2, newMatchList[i].player2);
item.AddButton(0, WatchButton, i, false, "Watch");
if (Connection.Instance.IsAdmin) {
item.AddButton(0, TerminateKickButton, 128 + i, false, "Terminate");
}
}
Matches.Clear();
matchList = newMatchList;
var root = Matches.CreateItem();
for (int i = 0; i < newMatchList.Count; i++) {
var item = Matches.CreateItem(root);
item.SetText(0, newMatchList[i].matchId.ToString());
item.SetText(1, newMatchList[i].player1);
item.SetText(2, newMatchList[i].player2);
item.AddButton(0, WatchButton, i, false, "Watch");
if (Connection.Instance.IsAdmin) {
item.AddButton(0, TerminateKickButton, 128 + i, false, "Terminate");
}
}
}
private void watchGame(TreeItem item, long column, long id, long mouseButtonIndex) {
if (mouseButtonIndex == 1 && column == 0 && id < 128) {
Connection.Instance.SendWatchGame(matchList[(int)id].matchId);
}
if (mouseButtonIndex == 1 && column == 0 && id < 128) {
Connection.Instance.SendWatchGame(matchList[(int)id].matchId);
}
}
private void terminateGame(TreeItem item, long column, long id, long mouseButtonIndex) {
if (mouseButtonIndex == 1 && column == 0 && id - 128 >= 0 && matchList[(int)id - 128] != null) {
Connection.Instance.TerminateGame(matchList[(int)id - 128].matchId);
}
if (mouseButtonIndex == 1 && column == 0 && id - 128 >= 0 && matchList[(int)id - 128] != null) {
Connection.Instance.TerminateGame(matchList[(int)id - 128].matchId);
}
}
private void kickPlayer(TreeItem item, long column, long id, long mouseButtonIndex) {
if (mouseButtonIndex == 1 && column == 0) {
Connection.Instance.KickPlayer(playerList[(int)id].Username);
}
if (mouseButtonIndex == 1 && column == 0) {
Connection.Instance.KickPlayer(playerList[(int)id].Username);
}
}
private void transitionToBoard() { GetTree().ChangeSceneToFile(BOARD_SCENE_PATH); }
}
}

View File

@@ -6,35 +6,35 @@ public partial class ConnectButtonUI : Button {
private const string BRACKET_SCENE_PATH = "res://scenes/bracket_view.tscn";
public override void _Ready() {
Connection.Instance.OnWsConnectionSuccess += OnConnectionSuccess;
Connection.Instance.OnWsConnectionFailed += OnConnectionFailed;
Connection.Instance.OnWsConnectionSuccess += OnConnectionSuccess;
Connection.Instance.OnWsConnectionFailed += OnConnectionFailed;
if (Connection.Instance.LastUsedConnectionAddress.Length > 0) {
AddressField.Text = Connection.Instance.LastUsedConnectionAddress;
}
if (Connection.Instance.LastUsedConnectionAddress.Length > 0) {
AddressField.Text = Connection.Instance.LastUsedConnectionAddress;
}
if (Connection.Instance.LastError.Length > 0) {
ErrorLabel.Text = Connection.Instance.LastError;
}
if (Connection.Instance.LastError.Length > 0) {
ErrorLabel.Text = Connection.Instance.LastError;
}
AddressField.GuiInput += e =>
{
if (AddressField.HasFocus() && e is InputEventKey inputEventKey && inputEventKey.IsPressed()) {
if (inputEventKey.KeyLabel == Key.Enter) {
Connection.Instance.Connect(AddressField.Text);
GetViewport().SetInputAsHandled();
}
AddressField.GuiInput += e =>
{
if (AddressField.HasFocus() && e is InputEventKey inputEventKey && inputEventKey.IsPressed()) {
if (inputEventKey.KeyLabel == Key.Enter) {
Connection.Instance.Connect(AddressField.Text);
GetViewport().SetInputAsHandled();
}
if (inputEventKey.KeyLabel == Key.Space) {
GetViewport().SetInputAsHandled();
}
}
};
if (inputEventKey.KeyLabel == Key.Space) {
GetViewport().SetInputAsHandled();
}
}
};
}
public override void _ExitTree() {
Connection.Instance.OnWsConnectionSuccess -= OnConnectionSuccess;
Connection.Instance.OnWsConnectionFailed -= OnConnectionFailed;
Connection.Instance.OnWsConnectionSuccess -= OnConnectionSuccess;
Connection.Instance.OnWsConnectionFailed -= OnConnectionFailed;
}
public override void _Pressed() { Connection.Instance.Connect(AddressField.Text); }
@@ -42,6 +42,6 @@ public partial class ConnectButtonUI : Button {
private void OnConnectionSuccess() { GetTree().ChangeSceneToFile(BRACKET_SCENE_PATH); }
private void OnConnectionFailed() {
ErrorLabel.Text = "Couldn't connect to server! " + Connection.Instance.LastError;
ErrorLabel.Text = "Couldn't connect to server! " + Connection.Instance.LastError;
}
}
}

View File

@@ -6,14 +6,14 @@ public partial class Connection : Node {
public const string WS_DEFAULT_ADDRESS = "wss://connect4.abunchofknowitalls.com";
private static TournamentType? parseTournamentType(string type) {
switch (type) {
case "RoundRobin":
return TournamentType.RoundRobin;
case "false":
return TournamentType.None;
default:
return null;
}
switch (type) {
case "RoundRobin":
return TournamentType.RoundRobin;
case "false":
return TournamentType.None;
default:
return null;
}
}
public static Connection Instance { get; private set; }
@@ -74,100 +74,98 @@ public partial class Connection : Node {
private float refreshGamePlayerListTimer = 5.0f;
public override void _Ready() {
Instance = this;
webSocket.SetHeartbeatInterval(5.0);
webSocket.HeartbeatInterval = 5.0;
Instance.OnWsDisconnect += () => GetTree().ChangeSceneToFile("res://scenes/main_menu.tscn");
Instance = this;
webSocket.SetHeartbeatInterval(5.0);
webSocket.HeartbeatInterval = 5.0;
Instance.OnWsDisconnect += () => GetTree().ChangeSceneToFile("res://scenes/main_menu.tscn");
}
public void Connect(string address) {
isConnecting = true;
LastUsedConnectionAddress = address;
if (isConnected) {
return;
}
isConnecting = true;
LastUsedConnectionAddress = address;
if (isConnected) {
return;
}
Error error = webSocket.ConnectToUrl(address);
if (error != Error.Ok) {
LastError = error.ToString();
}
Error error = webSocket.ConnectToUrl(address);
if (error != Error.Ok) {
LastError = error.ToString();
}
}
public override void _Process(double delta) {
webSocket.Poll();
WebSocketPeer.State state = webSocket.GetReadyState();
if (state == WebSocketPeer.State.Open) {
if (isConnecting) {
isConnecting = false;
isConnected = true;
LastError = "";
OnWsConnectionSuccess?.Invoke();
UpdateGameList();
UpdatePlayerList();
GetReservations();
refreshGamePlayerListTimer = 5.0f;
} else if (refreshGamePlayerListTimer <= 0.0f) {
UpdateGameList();
UpdatePlayerList();
GetReservations();
refreshGamePlayerListTimer = 5.0f;
} else {
refreshGamePlayerListTimer -= (float)delta;
}
webSocket.Poll();
WebSocketPeer.State state = webSocket.GetReadyState();
if (state == WebSocketPeer.State.Open) {
if (isConnecting) {
isConnecting = false;
isConnected = true;
LastError = "";
OnWsConnectionSuccess?.Invoke();
UpdateGameList();
UpdatePlayerList();
refreshGamePlayerListTimer = 5.0f;
} else if (refreshGamePlayerListTimer <= 0.0f) {
UpdateGameList();
UpdatePlayerList();
refreshGamePlayerListTimer = 5.0f;
} else {
refreshGamePlayerListTimer -= (float)delta;
}
while (webSocket.GetAvailablePacketCount() > 0) {
string message = webSocket.GetPacket().GetStringFromUtf8();
handleServerMessage(message);
}
while (webSocket.GetAvailablePacketCount() > 0) {
string message = webSocket.GetPacket().GetStringFromUtf8();
handleServerMessage(message);
}
if (shouldShowTournamentResults) {
var children = GetTree().Root.GetChildren();
foreach (var child in children) {
if (child.Name.ToString() == "BracketView") {
shouldShowTournamentResults = false;
ShowTournamentScoreboard(lastScoreboard);
}
}
}
} else if (state == WebSocketPeer.State.Connecting) {
// Do nothing
} else if (state == WebSocketPeer.State.Closing) {
// Do nothing
} else if (state == WebSocketPeer.State.Closed) {
if (isConnecting) {
isConnecting = false;
OnWsConnectionFailed?.Invoke();
} else if (isConnected) {
isConnected = false;
IsAdmin = false;
CurrentWaitTimeout = 5.0;
ActiveTournament = TournamentType.None;
DemoMode = false;
refreshGamePlayerListTimer = 5.0f;
var code = webSocket.GetCloseCode();
var reason = webSocket.GetCloseReason();
LastError = "Unexpected Disconnect. Reason: " + reason + ", Code: " + code;
GD.PrintErr("WebSocket closed with code: " + code + ", reason " + reason + ". Clean: " + (code != -1));
OnWsDisconnect?.Invoke();
}
}
if (shouldShowTournamentResults) {
var children = GetTree().Root.GetChildren();
foreach (var child in children) {
if (child.Name.ToString() == "BracketView") {
shouldShowTournamentResults = false;
ShowTournamentScoreboard(lastScoreboard);
}
}
}
} else if (state == WebSocketPeer.State.Connecting) {
// Do nothing
} else if (state == WebSocketPeer.State.Closing) {
// Do nothing
} else if (state == WebSocketPeer.State.Closed) {
if (isConnecting) {
isConnecting = false;
OnWsConnectionFailed?.Invoke();
} else if (isConnected) {
isConnected = false;
IsAdmin = false;
CurrentWaitTimeout = 5.0;
ActiveTournament = TournamentType.None;
DemoMode = false;
refreshGamePlayerListTimer = 5.0f;
var code = webSocket.GetCloseCode();
var reason = webSocket.GetCloseReason();
LastError = "Unexpected Disconnect. Reason: " + reason + ", Code: " + code;
GD.PrintErr("WebSocket closed with code: " + code + ", reason " + reason + ". Clean: " + (code != -1));
OnWsDisconnect?.Invoke();
}
}
}
// Player commands
public void SendConnect(string clientId) {
if (string.IsNullOrWhiteSpace(clientId)) {
GD.PrintErr("Client ID is required to CONNECT.");
return;
}
if (string.IsNullOrWhiteSpace(clientId)) {
GD.PrintErr("Client ID is required to CONNECT.");
return;
}
clientId = clientId.Trim();
clientId = clientId.Trim();
if (clientId.Contains(":")) {
GD.PrintErr("Client ID cannot contain ':' characters.");
return;
}
if (clientId.Contains(":")) {
GD.PrintErr("Client ID cannot contain ':' characters.");
return;
}
sendCommand("CONNECT", clientId);
sendCommand("CONNECT", clientId);
}
public void SendDisconnect() { sendCommand("DISCONNECT"); }
@@ -179,8 +177,8 @@ public partial class Connection : Node {
public void UpdatePlayerList() { sendCommand("PLAYER", "LIST"); }
public void SendWatchGame(int matchID) { sendCommand("GAME", "WATCH:" + matchID); }
public void AdminAuth(string password) {
if (IsAdmin) return;
sendCommand("ADMIN", "AUTH:" + password);
if (IsAdmin) return;
sendCommand("ADMIN", "AUTH:" + password);
}
public void GetMoveWait() { sendCommand("GET", "MOVE_WAIT"); }
public void GetTournamentStatus() { sendCommand("GET", "TOURNAMENT_STATUS"); }
@@ -189,23 +187,23 @@ public partial class Connection : Node {
// Admin commands
public void KickPlayer(string playerId) {
if (!IsAdmin) return;
sendCommand("ADMIN", "KICK:" + playerId);
if (!IsAdmin) return;
sendCommand("ADMIN", "KICK:" + playerId);
}
public void StartTournament(string tournamentType = "RoundRobin") {
if (!IsAdmin) return;
sendCommand("TOURNAMENT", "START:" + tournamentType);
if (!IsAdmin) return;
sendCommand("TOURNAMENT", "START:" + tournamentType);
}
public void CancelTournament() {
if (!IsAdmin) return;
sendCommand("TOURNAMENT", "CANCEL");
if (!IsAdmin) return;
sendCommand("TOURNAMENT", "CANCEL");
}
public void TerminateGame(int matchID) {
if (!IsAdmin) return;
sendCommand("GAME", "TERMINATE:" + matchID);
if (!IsAdmin) return;
sendCommand("GAME", "TERMINATE:" + matchID);
}
public void AwardGameWinner(int matchID, string winnerUsername) {
@@ -215,21 +213,21 @@ public partial class Connection : Node {
}
public void SetMoveWait(float waitTime) {
if (!IsAdmin) return;
CurrentWaitTimeout = waitTime;
sendCommand("SET", "MOVE_WAIT:" + waitTime);
if (!IsAdmin) return;
CurrentWaitTimeout = waitTime;
sendCommand("SET", "MOVE_WAIT:" + waitTime);
}
public void SetDemoMode(bool demoMode) {
if (!IsAdmin) return;
DemoMode = demoMode;
sendCommand("SET", "DEMO_MODE:" + demoMode);
if (!IsAdmin) return;
DemoMode = demoMode;
sendCommand("SET", "DEMO_MODE:" + demoMode);
}
public void SetMaxTimeout(float maxTimeout) {
if (!IsAdmin) return;
MaxTimeout = maxTimeout;
sendCommand("SET", "MAX_TIMEOUT:" + maxTimeout);
if (!IsAdmin) return;
MaxTimeout = maxTimeout;
sendCommand("SET", "MAX_TIMEOUT:" + maxTimeout);
}
public void AddReservation(string player1Username, string player2Username) {
@@ -248,155 +246,151 @@ public partial class Connection : Node {
}
private void sendCommand(string header, string body = "") {
if (!IsSocketOpen) {
GD.PrintErr($"Cannot send {header}, socket is not open.");
return;
}
if (!IsSocketOpen) {
GD.PrintErr($"Cannot send {header}, socket is not open.");
return;
}
string payload = string.IsNullOrEmpty(body) ? header : $"{header}:{body}";
webSocket.SendText(payload);
string payload = string.IsNullOrEmpty(body) ? header : $"{header}:{body}";
webSocket.SendText(payload);
}
private void handleServerMessage(string message) {
if (string.IsNullOrWhiteSpace(message)) {
return;
}
if (string.IsNullOrWhiteSpace(message)) {
return;
}
message = message.Trim();
message = message.Trim();
string header;
string body;
int separatorIndex = message.IndexOf(':');
if (separatorIndex >= 0) {
header = message.Substring(0, separatorIndex).Trim();
body = message.Substring(separatorIndex + 1).Trim();
} else {
header = message.Trim();
body = string.Empty;
}
string header;
string body;
int separatorIndex = message.IndexOf(':');
if (separatorIndex >= 0) {
header = message.Substring(0, separatorIndex).Trim();
body = message.Substring(separatorIndex + 1).Trim();
} else {
header = message.Trim();
body = string.Empty;
}
header = header.ToUpperInvariant();
header = header.ToUpperInvariant();
switch (header) {
case "CONNECT":
if (body.Equals("ACK", StringComparison.OrdinalIgnoreCase)) {
IsPlayer = true;
OnConnected?.Invoke();
}
switch (header) {
case "CONNECT":
if (body.Equals("ACK", StringComparison.OrdinalIgnoreCase)) {
IsPlayer = true;
OnConnected?.Invoke();
}
break;
case "READY":
if (body.Equals("ACK", StringComparison.OrdinalIgnoreCase)) {
OnReadyAcknowledged?.Invoke();
}
break;
case "READY":
if (body.Equals("ACK", StringComparison.OrdinalIgnoreCase)) {
OnReadyAcknowledged?.Invoke();
}
break;
case "GAME":
handleGameMessage(body);
break;
case "PLAYER":
handlePlayerList(body);
break;
case "OPPONENT":
if (int.TryParse(body, out int column)) {
OnOpponentMove?.Invoke(column);
} else {
GD.PrintErr($"Invalid opponent column: {body}");
}
break;
case "GAME":
handleGameMessage(body);
break;
case "PLAYER":
handlePlayerList(body);
break;
case "OPPONENT":
if (int.TryParse(body, out int column)) {
OnOpponentMove?.Invoke(column);
} else {
GD.PrintErr($"Invalid opponent column: {body}");
}
break;
case "ADMIN":
if (body == "AUTH:ACK") {
IsAdmin = true;
GetMoveWait();
GetTournamentStatus();
GetReservations();
OnBecomeAdmin?.Invoke();
}
break;
case "ADMIN":
if (body == "AUTH:ACK") {
IsAdmin = true;
GetMoveWait();
GetTournamentStatus();
OnBecomeAdmin?.Invoke();
}
break;
case "TOURNAMENT":
handleTournamentMessage(body);
break;
case "RESERVATION":
handleReservationMessage(body);
break;
case "GET":
string data = body.Split(":")[1];
if (body.StartsWith("MOVE_WAIT")) {
CurrentWaitTimeout = double.Parse(data);
} else if (body.StartsWith("MAX_TIMEOUT")) {
MaxTimeout = double.Parse(data);
} else if (body.StartsWith("DEMO_MODE")) {
DemoMode = bool.Parse(data);
} else if (body.StartsWith("TOURNAMENT_STATUS")) {
TournamentType? type = parseTournamentType(data);
break;
case "TOURNAMENT":
handleTournamentMessage(body);
break;
case "GET":
string data = body.Split(":")[1];
if (body.StartsWith("MOVE_WAIT")) {
CurrentWaitTimeout = double.Parse(data);
} else if (body.StartsWith("MAX_TIMEOUT")) {
MaxTimeout = double.Parse(data);
} else if (body.StartsWith("DEMO_MODE")) {
DemoMode = bool.Parse(data);
} else if (body.StartsWith("TOURNAMENT_STATUS")) {
TournamentType? type = parseTournamentType(data);
if (type == null) {
GD.PrintErr($"Unhandled tournament type: {data}");
} else {
ActiveTournament = type.Value;
}
} else {
GD.PrintErr($"Unhandled data get: {body}");
}
if (type == null) {
GD.PrintErr($"Unhandled tournament type: {data}");
} else {
ActiveTournament = type.Value;
}
} else {
GD.PrintErr($"Unhandled data get: {body}");
}
OnGetDataAcks?.Invoke();
break;
case "SET":
OnSetDataAcks?.Invoke();
break;
case "ERROR":
GD.PrintErr(message);
OnError?.Invoke(message);
break;
default:
GD.Print($"Unhandled server message: {message}");
break;
}
OnGetDataAcks?.Invoke();
break;
case "SET":
OnSetDataAcks?.Invoke();
break;
case "ERROR":
GD.PrintErr(message);
OnError?.Invoke(message);
break;
default:
GD.Print($"Unhandled server message: {message}");
break;
}
}
private void handleTournamentMessage(string body) {
if (string.IsNullOrWhiteSpace(body)) {
return;
}
if (string.IsNullOrWhiteSpace(body)) {
return;
}
string[] segments = body.Split(':');
string command = segments[0].Trim().ToUpperInvariant();
string argument = segments.Length > 1 ? segments[1].Trim() : string.Empty;
string[] segments = body.Split(':');
string command = segments[0].Trim().ToUpperInvariant();
string argument = segments.Length > 1 ? segments[1].Trim() : string.Empty;
switch (command) {
case "END": {
ActiveTournament = TournamentType.None;
List<(string, int)> playerScoreboard = new List<(string, int)>();
string[] entries = segments[1].Split("|");
foreach (string entry in entries) {
string[] data = entry.Split(',');
playerScoreboard.Add((data[0], int.Parse(data[1])));
}
switch (command) {
case "END": {
ActiveTournament = TournamentType.None;
List<(string, int)> playerScoreboard = new List<(string, int)>();
string[] entries = segments[1].Split("|");
foreach (string entry in entries) {
string[] data = entry.Split(',');
playerScoreboard.Add((data[0], int.Parse(data[1])));
}
lastScoreboard = playerScoreboard;
shouldShowTournamentResults = true;
OnTournamentEnd?.Invoke();
break;
}
case "START": {
TournamentType? type = parseTournamentType(argument);
if (type == null) {
GD.PrintErr($"Unhandled tournament type: {argument}");
} else {
ActiveTournament = type.Value;
OnStartTournament?.Invoke();
}
lastScoreboard = playerScoreboard;
shouldShowTournamentResults = true;
OnTournamentEnd?.Invoke();
break;
}
case "START": {
TournamentType? type = parseTournamentType(argument);
if (type == null) {
GD.PrintErr($"Unhandled tournament type: {argument}");
} else {
ActiveTournament = type.Value;
OnStartTournament?.Invoke();
}
break;
}
case "CANCEL": {
ActiveTournament = TournamentType.None;
OnCancelTournamentAck?.Invoke();
break;
}
}
break;
}
case "CANCEL": {
ActiveTournament = TournamentType.None;
OnCancelTournamentAck?.Invoke();
break;
}
}
}
private void handleReservationMessage(string body) {
@@ -453,151 +447,151 @@ public partial class Connection : Node {
}
private void handlePlayerList(string body) {
if (string.IsNullOrWhiteSpace(body)) {
return;
}
if (string.IsNullOrWhiteSpace(body)) {
return;
}
string[] segments = body.Split(':');
string command = segments[0].Trim().ToUpperInvariant();
string[] segments = body.Split(':');
string command = segments[0].Trim().ToUpperInvariant();
switch (command) {
case "LIST": {
List<PlayerData> players = new List<PlayerData>();
switch (command) {
case "LIST": {
List<PlayerData> players = new List<PlayerData>();
if (segments.Length < 2) {
OnUpdatedPlayers?.Invoke(players);
break;
}
if (segments.Length < 2) {
OnUpdatedPlayers?.Invoke(players);
break;
}
string[] entries = segments[1].Split("|");
foreach (string entry in entries) {
string[] data = entry.Split(',');
players.Add(new PlayerData(data[0], bool.Parse(data[1]), bool.Parse(data[2])));
}
string[] entries = segments[1].Split("|");
foreach (string entry in entries) {
string[] data = entry.Split(',');
players.Add(new PlayerData(data[0], bool.Parse(data[1]), bool.Parse(data[2])));
}
OnUpdatedPlayers?.Invoke(players);
break;
}
}
OnUpdatedPlayers?.Invoke(players);
break;
}
}
}
private void handleGameMessage(string body) {
if (string.IsNullOrWhiteSpace(body)) {
return;
}
if (string.IsNullOrWhiteSpace(body)) {
return;
}
string[] segments = body.Split(':');
string command = segments[0].Trim().ToUpperInvariant();
string argument = segments.Length > 1 ? segments[1].Trim() : string.Empty;
string[] segments = body.Split(':');
string command = segments[0].Trim().ToUpperInvariant();
string argument = segments.Length > 1 ? segments[1].Trim() : string.Empty;
if (IsPlayer) {
switch (command) {
case "START":
bool isFirst = argument == "1" || argument.Equals("TRUE", StringComparison.OrdinalIgnoreCase);
OnGameStart?.Invoke(isFirst);
break;
case "WINS":
OnGameWin?.Invoke();
break;
case "LOSS":
OnGameLoss?.Invoke();
break;
case "DRAW":
OnGameDraw?.Invoke();
break;
case "TERMINATED":
OnGameTerminated?.Invoke();
break;
default:
GD.Print($"Unhandled GAME message: {body}");
break;
}
} else // Regular observer/admin
{
switch (command) {
case "WIN":
OnObserveWin?.Invoke(segments[1]);
break;
case "MOVE":
OnObserveMove?.Invoke(segments[1], int.Parse(segments[2]));
break;
case "DRAW":
OnObserveDraw?.Invoke();
break;
case "TERMINATED":
OnObserveTerminated?.Invoke();
break;
case "LIST":
List<MatchData> matches = new List<MatchData>();
if (IsPlayer) {
switch (command) {
case "START":
bool isFirst = argument == "1" || argument.Equals("TRUE", StringComparison.OrdinalIgnoreCase);
OnGameStart?.Invoke(isFirst);
break;
case "WINS":
OnGameWin?.Invoke();
break;
case "LOSS":
OnGameLoss?.Invoke();
break;
case "DRAW":
OnGameDraw?.Invoke();
break;
case "TERMINATED":
OnGameTerminated?.Invoke();
break;
default:
GD.Print($"Unhandled GAME message: {body}");
break;
}
} else // Regular observer/admin
{
switch (command) {
case "WIN":
OnObserveWin?.Invoke(segments[1]);
break;
case "MOVE":
OnObserveMove?.Invoke(segments[1], int.Parse(segments[2]));
break;
case "DRAW":
OnObserveDraw?.Invoke();
break;
case "TERMINATED":
OnObserveTerminated?.Invoke();
break;
case "LIST":
List<MatchData> matches = new List<MatchData>();
if (segments.Length < 2) {
OnUpdatedMatches?.Invoke(matches);
break;
}
if (segments.Length < 2) {
OnUpdatedMatches?.Invoke(matches);
break;
}
string[] entries = segments[1].Split("|");
foreach (string entry in entries) {
string[] data = entry.Split(',');
matches.Add(new MatchData(int.Parse(data[0]), data[1], data[2]));
}
string[] entries = segments[1].Split("|");
foreach (string entry in entries) {
string[] data = entry.Split(',');
matches.Add(new MatchData(int.Parse(data[0]), data[1], data[2]));
}
OnUpdatedMatches?.Invoke(matches);
break;
case "WATCH":
CurrentObservingMatch = null;
PreviousMoves.Clear();
string[] activeMatchData = segments[2].Split("|");
if (activeMatchData.IsEmpty()) {
string[] matchData = segments[2].Split(',');
CurrentObservingMatch = new MatchData(int.Parse(matchData[0]), matchData[1], matchData[2]);
} else {
string[] matchData = activeMatchData[0].Split(',');
CurrentObservingMatch = new MatchData(int.Parse(matchData[0]), matchData[1], matchData[2]);
for (int i = 1; i < activeMatchData.Length; i++) {
string[] moveData = activeMatchData[i].Split(',');
PreviousMoves.Add((moveData[0], int.Parse(moveData[1])));
}
}
OnUpdatedMatches?.Invoke(matches);
break;
case "WATCH":
CurrentObservingMatch = null;
PreviousMoves.Clear();
string[] activeMatchData = segments[2].Split("|");
if (activeMatchData.IsEmpty()) {
string[] matchData = segments[2].Split(',');
CurrentObservingMatch = new MatchData(int.Parse(matchData[0]), matchData[1], matchData[2]);
} else {
string[] matchData = activeMatchData[0].Split(',');
CurrentObservingMatch = new MatchData(int.Parse(matchData[0]), matchData[1], matchData[2]);
for (int i = 1; i < activeMatchData.Length; i++) {
string[] moveData = activeMatchData[i].Split(',');
PreviousMoves.Add((moveData[0], int.Parse(moveData[1])));
}
}
OnWatchGameAck?.Invoke();
break;
default:
GD.Print($"Unhandled GAME message: {body}");
break;
}
}
OnWatchGameAck?.Invoke();
break;
default:
GD.Print($"Unhandled GAME message: {body}");
break;
}
}
}
public void ShowTournamentScoreboard(List<(string, int)> playerScoreboard) {
var scoreboardWindow = new Window();
scoreboardWindow.Theme = GD.Load<Theme>("res://assets/theme.tres");
scoreboardWindow.AlwaysOnTop = true;
scoreboardWindow.MaximizeDisabled = true;
scoreboardWindow.Unresizable = true;
scoreboardWindow.InitialPosition = Window.WindowInitialPosition.CenterMainWindowScreen;
scoreboardWindow.Size = new Vector2I(256, 512);
scoreboardWindow.CloseRequested += () => { GetTree().Root.RemoveChild(scoreboardWindow); };
var scoreboardWindow = new Window();
scoreboardWindow.Theme = GD.Load<Theme>("res://assets/theme.tres");
scoreboardWindow.AlwaysOnTop = true;
scoreboardWindow.MaximizeDisabled = true;
scoreboardWindow.Unresizable = true;
scoreboardWindow.InitialPosition = Window.WindowInitialPosition.CenterMainWindowScreen;
scoreboardWindow.Size = new Vector2I(256, 512);
scoreboardWindow.CloseRequested += () => { GetTree().Root.RemoveChild(scoreboardWindow); };
var tree = new Tree();
tree.HideRoot = true;
tree.Columns = 2;
tree.ColumnTitlesVisible = true;
tree.Theme = GD.Load<Theme>("res://assets/theme.tres");
tree.GrowHorizontal = Control.GrowDirection.Both;
tree.GrowVertical = Control.GrowDirection.Both;
tree.SetColumnTitle(0, "Player");
tree.SetColumnTitle(1, "Score");
var root = tree.CreateItem();
var tree = new Tree();
tree.HideRoot = true;
tree.Columns = 2;
tree.ColumnTitlesVisible = true;
tree.Theme = GD.Load<Theme>("res://assets/theme.tres");
tree.GrowHorizontal = Control.GrowDirection.Both;
tree.GrowVertical = Control.GrowDirection.Both;
tree.SetColumnTitle(0, "Player");
tree.SetColumnTitle(1, "Score");
var root = tree.CreateItem();
foreach ((string, int) entry in playerScoreboard) {
var item = tree.CreateItem(root);
item.SetText(0, entry.Item1);
item.SetText(1, entry.Item2.ToString());
}
foreach ((string, int) entry in playerScoreboard) {
var item = tree.CreateItem(root);
item.SetText(0, entry.Item1);
item.SetText(1, entry.Item2.ToString());
}
scoreboardWindow.AddChild(tree);
tree.SetAnchorsPreset(Control.LayoutPreset.FullRect);
scoreboardWindow.AddChild(tree);
tree.SetAnchorsPreset(Control.LayoutPreset.FullRect);
GetTree().Root.AddChild(scoreboardWindow);
GetTree().Root.AddChild(scoreboardWindow);
}
}

View File

@@ -0,0 +1 @@
uid://dwb6ioubllb24