Files
FunGameServer-Test/modules/FunGame.Server.Modules.Melee/MeleeGameModuleServer.cs
T
2026-08-28 19:44:46 +08:00

135 lines
5.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Concurrent;
using FunGame.Core.Entity;
using FunGame.Core.Library.Constant;
using FunGame.Core.Model.Framework;
using FunGame.Core.Model.Queue;
using FunGame.Server.Contracts.Gaming;
using FunGame.Server.Contracts.Networking;
using FunGame.Server.Contracts.Plugins;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FunGame.Server.Modules.Melee;
/// <summary>
/// 标准近战 GameModule(游戏模式模组):封装网络层在 MixGamingQueue 之上<para/>
/// 参考 v2 ExampleGameModuleServer:单例模组、按房间建 Worker(GamingObject 对应物)、
/// GamingType switch-case 处理玩家行动;内容层(角色/技能/物品/Effect)经 GameModuleDepend 声明依赖。<para/>
/// 当前为 Phase 0:建房(StartGameAsync)+ 连接确认 + 选角;Attack/Skill/Item 等玩家局内决策后续接入。
/// </summary>
public class MeleeGameModuleServer : IGameModuleServer
{
public string Name => "melee";
public string Version => "0.1.0";
public string Author => "FunGame.Server";
public string Description => "标准近战游戏模式:淘汰制死亡竞赛(最多复活 1 次),封装网络层在 MixGamingQueue 上";
public string Id => Name;
public GameModuleDepend Dependencies { get; } = new(
maps: [],
characters: ["example", "oshima"],
skills: ["example", "oshima"],
items: ["example", "oshima"]);
public string DefaultMap => "";
public RoomType RoomType => RoomType.Mix;
public int MaxUsers => 8;
private ILogger? _logger;
/// <summary>房间工作区:游戏 Id ->(角色池 / 已连接用户 / 用户角色选择)</summary>
private sealed record Worker(List<Character> Characters, HashSet<long> ConnectedUsers, Dictionary<long, Character> UserCharacters);
private readonly ConcurrentDictionary<Guid, Worker> _workers = new();
public void OnLoad(IServiceProvider services)
{
_logger = services.GetService<ILoggerFactory>()?.CreateLogger("GameModule.melee");
_logger?.LogInformation("MeleeGameModuleServer v{Version} 已加载", Version);
}
public void OnUnload()
{
_logger?.LogInformation("MeleeGameModuleServer 即将卸载(活跃对局 {Count})", _workers.Count);
_workers.Clear();
}
/// <summary>建房:创建 MixGamingQueue(沿用宿主当前淘汰/复活=1 配置),登记房间工作区</summary>
public Task<GamingQueue> StartGameAsync(IGameSession session, params object[] args)
{
List<Character> characters = args.Length > 0 && args[0] is List<Character> list ? list : [];
GameMap? map = args.Length > 1 ? args[1] as GameMap : null;
MixGamingQueue queue = new(characters, msg => _logger?.LogDebug("[Melee {GameId}] {Msg}", session.Id, msg))
{
IsDebug = false,
MaxRespawnTimes = 1
};
if (map != null)
{
queue.LoadGameMap(map);
}
queue.InitActionQueue();
_workers[session.Id] = new Worker(characters, [], []);
_logger?.LogInformation("Melee 对局 {GameId} 开始({Count} 名角色)", session.Id, characters.Count);
return Task.FromResult<GamingQueue>(queue);
}
/// <summary>处理客户端局内消息(switch-case GamingType,参考 v2)</summary>
public Task<Dictionary<string, object>?> HandleGamingMessageAsync(IGameSession session, IClientSession client, GamingType type, Dictionary<string, object> data)
{
if (!_workers.TryGetValue(session.Id, out Worker? worker))
{
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object> { ["error"] = "对局工作区不存在" });
}
long userId = client.UserId ?? client.SessionId;
switch (type)
{
case GamingType.Connect:
worker.ConnectedUsers.Add(userId);
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object>
{
["msg"] = "连接确认成功",
["connected"] = worker.ConnectedUsers.Count,
["total"] = worker.Characters.Count
});
case GamingType.PickCharacter:
{
long id = GetLong(data, "id");
Character? character = worker.Characters.FirstOrDefault(c => c.Id == id);
if (character == null)
{
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object> { ["error"] = $"角色不存在:{id}" });
}
worker.UserCharacters[userId] = character;
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object>
{
["msg"] = $"已选择角色:{character.NickName ?? character.Name}",
["id"] = character.Id
});
}
case GamingType.Surrender:
_ = session.EndGameAsync();
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object> { ["msg"] = "对局已结束" });
default:
// Attack/Skill/Item/Move/Magic/Buy/... 玩家局内决策接入后续里程碑实现
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object>
{
["msg"] = $"已收到 {type}(玩家局内决策接入后续实现)",
["round"] = session.Queue.TotalRound
});
}
}
private static long GetLong(Dictionary<string, object> data, string key)
=> data.TryGetValue(key, out object? value) && long.TryParse(value?.ToString(), out long result) ? result : 0;
}