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 QuickJoin(int gameType, int level) { var rooms = _redisService.GetGameRoomAllList(); if(rooms==null || rooms.Count()==0) return new BaseResponse(); 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 { Code = CommonResponseCodeEnum.Error, Info = "暂无可用房间" }; var room = candidates[Random.Shared.Next(candidates.Count)]; var wsUrl = ResolveWebSocketUrl(room.RoomId); return new BaseResponse { Data = new QuickJoinResult { RoomId = room.RoomId, WebSocketUrl = wsUrl } }; } private string ResolveWebSocketUrl(string roomId) { var instances = _configuration.GetSection("GameServerInstances").Get>(); if (instances == null || instances.Count == 0) return ""; return instances[0]; } [HttpGet("Assign")] public BaseResponse AssignRoom(string roomId) { if (string.IsNullOrWhiteSpace(roomId)) return new BaseResponse { Code = CommonResponseCodeEnum.ParamError, Info = "roomId 不能为空" }; var wsUrl = ResolveWebSocketUrl(roomId); if (string.IsNullOrEmpty(wsUrl)) return new BaseResponse { Code = CommonResponseCodeEnum.Error, Info = "未配置游戏服务器实例" }; return new BaseResponse { Data = wsUrl }; } } }