feat: add minigame room player service
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
053a95b4fb
commit
31afce6882
@@ -0,0 +1,82 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace XWorld.Framework
|
||||
{
|
||||
public interface IRoomPlayerService
|
||||
{
|
||||
IReadOnlyList<PlayerInfo> GetRoomPlayers();
|
||||
bool TryGetRoomPlayer(int playerId, out PlayerInfo player);
|
||||
void RequestPlayerInfo(int playerId, Action<PlayerInfo> onLoaded);
|
||||
}
|
||||
|
||||
public sealed class RoomPlayerService : IRoomPlayerService
|
||||
{
|
||||
private readonly List<PlayerInfo> _players = new List<PlayerInfo>();
|
||||
private readonly Dictionary<int, PlayerInfo> _byId = new Dictionary<int, PlayerInfo>();
|
||||
|
||||
public void SetRoomPlayers(IEnumerable<PlayerInfo> players)
|
||||
{
|
||||
_players.Clear();
|
||||
_byId.Clear();
|
||||
|
||||
if (players == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (PlayerInfo player in players)
|
||||
{
|
||||
if (player == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
PlayerInfo copy = Clone(player);
|
||||
_players.Add(copy);
|
||||
_byId[copy.PlayerId] = copy;
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<PlayerInfo> GetRoomPlayers()
|
||||
{
|
||||
var copy = new List<PlayerInfo>(_players.Count);
|
||||
for (int i = 0; i < _players.Count; i++)
|
||||
{
|
||||
copy.Add(Clone(_players[i]));
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
public bool TryGetRoomPlayer(int playerId, out PlayerInfo player)
|
||||
{
|
||||
if (_byId.TryGetValue(playerId, out PlayerInfo cached))
|
||||
{
|
||||
player = Clone(cached);
|
||||
return true;
|
||||
}
|
||||
|
||||
player = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void RequestPlayerInfo(int playerId, Action<PlayerInfo> onLoaded)
|
||||
{
|
||||
TryGetRoomPlayer(playerId, out PlayerInfo player);
|
||||
onLoaded?.Invoke(player);
|
||||
}
|
||||
|
||||
private static PlayerInfo Clone(PlayerInfo source)
|
||||
{
|
||||
return new PlayerInfo
|
||||
{
|
||||
PlayerId = source.PlayerId,
|
||||
Name = source.Name,
|
||||
IsAI = source.IsAI,
|
||||
Level = source.Level,
|
||||
AppearanceType = source.AppearanceType,
|
||||
AvatarId = source.AvatarId,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user