AceField/Scripts/UI/Leaderboard.cs
2024-08-09 15:45:40 +08:00

68 lines
1.5 KiB
C#

using System.Linq;
using AceField.Scripts.Logic;
using Godot;
namespace AceField.Scripts.UI;
public partial class Leaderboard : Control
{
[Export] public Scoreboard Scoreboard;
public override void _Process(double delta)
{
Visible = Input.IsActionPressed("ui_leaderboard");
if (!Visible) return;
if (Scoreboard.Players.Count == 1) return;
if (GetNode<Control>("List").GetChildCount() != Scoreboard.Players.Count)
{
CleanNodes();
CreateNodes();
return;
}
var place = 1;
var data = Scoreboard.Players.ToList();
data.Sort((a, b) => b.Value.Score.CompareTo(a.Value.Score));
foreach (var item in data)
{
var record = GetNode<Control>("List").GetNode<LeaderboardRecord>($"Record_{place}");
record!.PlayerId = item.Key;
record.Place = place;
record.Score = item.Value.Score;
record.PlayerName = item.Value.Name;
place++;
}
}
private void CleanNodes()
{
foreach (var child in GetNode<Control>("List").GetChildren())
{
child.QueueFree();
}
}
private void CreateNodes()
{
var blueprint = GD.Load<PackedScene>("res://Scenes/UI/LeaderboardRecord.tscn");
var place = 1;
foreach (var record in Scoreboard.Players)
{
var instance = blueprint.Instantiate<LeaderboardRecord>();
instance.Place = place;
instance.PlayerName = record.Value.Name;
instance.Score = record.Value.Score;
instance.PlayerId = record.Key;
instance.CustomMinimumSize = new Vector2(0, 80);
instance.Name = $"Record_{place}";
GetNode("List").AddChild(instance);
place++;
}
}
}