AceField/Scripts/Logic/Scoreboard.cs
2024-08-09 13:49:04 +08:00

70 lines
1.6 KiB
C#

using System.Collections.Generic;
using Godot;
namespace AceField.Scripts.Logic;
public record PlayerData(string Name, int Score = 0)
{
public string Name { get; set; } = Name;
public int Score { get; set; } = Score;
};
public partial class Scoreboard : Node
{
public Dictionary<int, PlayerData> Players = new();
public void AddPlayer(int networkId, string playerName = null)
{
Rpc(nameof(UpdateEntry), networkId, 0, playerName ?? $"Player#{networkId}");
}
public void RemovePlayer(int networkId)
{
Rpc(nameof(DropEntry), networkId);
}
public void AddScore(int networkId, int amount = 1)
{
if (!Players.TryGetValue(networkId, out var player)) return;
player.Score += amount;
Rpc(nameof(UpdateEntry), networkId, player.Score, player.Name);
}
public void SetName(int networkId, string name)
{
if (!Players.TryGetValue(networkId, out var player)) return;
player.Name = name;
Rpc(nameof(UpdateEntry), networkId, player.Score, player.Name);
}
public PlayerData GetData(int networkId)
{
return Players.GetValueOrDefault(networkId);
}
public PlayerData GetCurrentData()
{
return Players.GetValueOrDefault(Multiplayer.GetUniqueId());
}
[Rpc(MultiplayerApi.RpcMode.AnyPeer, CallLocal = true)]
private void UpdateEntry(int networkId, int score, string name)
{
if (Players.ContainsKey(networkId))
{
Players[networkId].Score = score;
Players[networkId].Name = name;
}
else
{
Players.Add(networkId, new PlayerData(name, score));
}
}
[Rpc(MultiplayerApi.RpcMode.AnyPeer, CallLocal = true)]
private void DropEntry(int networkId)
{
Players.Remove(networkId);
}
}