72 lines
2.5 KiB
C#
72 lines
2.5 KiB
C#
using Common;
|
|
using CommonDomain.Enum;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using RedisService;
|
|
|
|
namespace FishGameHost.Controllers
|
|
{
|
|
[ApiController, Route("api/[controller]")]
|
|
public class RoomController : ControllerBase
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
private readonly IRedisService _redisService;
|
|
|
|
public RoomController(IConfiguration configuration, IRedisService redisService)
|
|
{
|
|
_configuration = configuration;
|
|
_redisService = redisService;
|
|
}
|
|
|
|
public class QuickJoinResult
|
|
{
|
|
public string RoomId { get; set; } = "";
|
|
public string WebSocketUrl { get; set; } = "";
|
|
}
|
|
|
|
[HttpGet("QuickJoin")]
|
|
public BaseResponse<QuickJoinResult> QuickJoin(int gameType, int level)
|
|
{
|
|
var rooms = _redisService.GetGameRoomAllList();
|
|
|
|
if(rooms==null || rooms.Count()==0)
|
|
return new BaseResponse<QuickJoinResult>();
|
|
var candidates = rooms?.Where(r =>
|
|
r != null &&
|
|
(int)r.GameType == gameType &&
|
|
(level == 0 || r.RoomLevel == level) &&
|
|
(r.Players?.Count ?? 0) < r.MaxPlayerCount).ToList();
|
|
|
|
if (candidates == null || candidates.Count == 0)
|
|
return new BaseResponse<QuickJoinResult> { Code = CommonResponseCodeEnum.Error, Info = "暂无可用房间" };
|
|
|
|
var room = candidates[Random.Shared.Next(candidates.Count)];
|
|
|
|
var wsUrl = ResolveWebSocketUrl(room.RoomId);
|
|
return new BaseResponse<QuickJoinResult> { Data = new QuickJoinResult { RoomId = room.RoomId, WebSocketUrl = wsUrl } };
|
|
}
|
|
|
|
private string ResolveWebSocketUrl(string roomId)
|
|
{
|
|
var instances = _configuration.GetSection("GameServerInstances").Get<List<string>>();
|
|
if (instances == null || instances.Count == 0)
|
|
return "";
|
|
|
|
return instances[0];
|
|
}
|
|
|
|
[HttpGet("Assign")]
|
|
public BaseResponse<string> AssignRoom(string roomId)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(roomId))
|
|
return new BaseResponse<string> { Code = CommonResponseCodeEnum.ParamError, Info = "roomId 不能为空" };
|
|
|
|
var wsUrl = ResolveWebSocketUrl(roomId);
|
|
if (string.IsNullOrEmpty(wsUrl))
|
|
return new BaseResponse<string> { Code = CommonResponseCodeEnum.Error, Info = "未配置游戏服务器实例" };
|
|
|
|
return new BaseResponse<string> { Data = wsUrl };
|
|
}
|
|
|
|
}
|
|
}
|