/// <summary> /// 将用户添加到创建好的房间内 /// </summary> /// <param name="userId"></param> /// <param name="room"></param> private void AddUserToRoom(int userId, MatchRoom room) { room.TeamOne.Add(userId); roomMap.TryAdd(room.Id, room); userRoom.TryAdd(userId, room.Id); }
/// <summary> /// 将用户添加到创建好的房间内 /// </summary> /// <param name="userId"></param> /// <param name="room"></param> private void AddUserToRoom(int userId, MatchRoom room) { room.TeamOne.Add(userId); roomMap.TryAdd(room.Id, room); userRoom.TryAdd(userId, room.Id); }
/// <summary> /// 创建房间从缓存数据中 /// </summary> /// <param name="userId"></param> /// <param name="room"></param> private void CreateRoomFromCache(int userId, out MatchRoom room) { if (cacheRooms.Count > 0) { cacheRooms.TryPop(out room); AddUserToRoom(userId, room); } else { room = new MatchRoom(); room.Id = AddIndex; AddUserToRoom(userId, room); } }
private void Enter(UserToken token) { int userId = GetUserId(token); //判断是否正在匹配的房间中 if (!userRoom.ContainsKey(userId)) { MatchRoom room = null; bool isEnter = false; //当前是否有在等待中的房间 if (roomMap.Count > 0) { //遍历所有等待中的房间 foreach (MatchRoom item in roomMap.Values) { //如果没满员 if (item.TeamMax * 2 > item.TeamOne.Count + item.TeamTwo.Count) { room = item; //如果队伍一没满员则进入队伍1 if (room.TeamOne.Count < room.TeamMax) { room.TeamOne.Add(userId); } else { room.TeamTwo.Add(userId); } //添加玩家与房间的映射关系 isEnter = true; userRoom.TryAdd(userId, room.Id); break; } } //当所有房间全部满员 判断缓存中是否有房间 if (!isEnter) { CreateRoomFromCache(userId, out room); } } else { //没有等待中的房间 CreateRoomFromCache(userId, out room); } //不管什么方式进入房间,判断房间是否满员,满了就开始选人,将房间丢进缓存队列 if (room.TeamOne.Count == room.TeamTwo.Count && room.TeamOne.Count == room.TeamMax) { //通知选人模块开始选人 EventUtil.createSelect(room.TeamOne, room.TeamTwo); WriteToUsers(room.TeamOne.ToArray(), GetType(), 0, MatchProtocol.ENTER_DELECT_BRO, null); WriteToUsers(room.TeamTwo.ToArray(), GetType(), 0, MatchProtocol.ENTER_DELECT_BRO, null); //移除玩家映射 foreach (int item in room.TeamOne) { int i; userRoom.TryRemove(item, out i); } foreach (int item in room.TeamTwo) { int i; userRoom.TryRemove(item, out i); } //重置房间数据 room.TeamOne.Clear(); room.TeamTwo.Clear(); //将房间从等待房间中移除 roomMap.TryRemove(room.Id, out room); //加入缓存 cacheRooms.Push(room); } } }