public static async Task <(bool, StartPlayReply, long)> RestoreMatchUser(Session session)
        {
            Log.Information($"RestoreMatchUser  session:{session.session_id}, user_no:{session.user_no}");
            (var success, var match_id, var timeToLive) = await MatchUser.GetMatchUser(session.user_no);

            if (success == false)
            {
                Log.Information($"RestoreMatchUser cannot find session:{session.session_id}, user_no:{session.user_no}");
                return(false, null, 0);
            }

            // 잠시 동안 유저는 할당했지만 아직 매칭 정보가 새팅중일수 있다.
            (var match_success, var reply) = await Match.LoadMatch(match_id);

            if (match_success == false)
            {
                Log.Information($"RestoreMatchUser LoadMatch false session:{session.session_id}, user_no:{session.user_no}");

                if (timeToLive != null)
                {
                    // 일정 시간 이후에도 매칭 정보가 없다면 해당 유저 할당을 강제 해지하여 매칭이 되도록 한다.
                    if ((match_waiting_expire - (TimeSpan)timeToLive).TotalSeconds > 3)
                    {
                        await MatchUser.RemoveMatchUser(session.user_no);
                    }
                }
                return(false, null, 0);
            }

            return(true, reply, match_id);
        }
        /// <summary>
        /// 매칭 조건이 맞지 않아 대기
        /// </summary>
        /// <param name="session"></param>
        /// <param name="request"></param>
        /// <param name="responseStream"></param>
        /// <returns></returns>
        public static async Task WaitStartPlay(Session session, StartPlayRequest request, IServerStreamWriter <StartPlayReply> responseStream)
        {
            // 대기자로 등록
            await MatchUser.RemoveMatchUser(session.user_no);

            await WaitingList.AddWaitingUser(new WaitingUser()
            {
                map_id = session.map_id, rank = session.rank
            }, session.user_no);
        }
Пример #3
0
        /// <summary>
        /// 게임 결과 기다림
        /// </summary>
        /// <param name="session"></param>
        /// <param name="request"></param>
        /// <param name="responseStream"></param>
        /// <returns></returns>
        public static async Task WaitGameResult(Session session, string channel_id, JMapData map_data, JGameModeData game_mode)
        {
            string key = $"game_result:{channel_id}";

            Log.Information($"WaitGameResult {key}");

            Interlocked.Increment(ref RankMatchmaking.MatchCount);

            var queue = Cache.Instance.GetSubscriber().Subscribe(key);

            var cts = new CancellationTokenSource();

            cts.CancelAfter((int)game_result_expire.TotalMilliseconds);
            try
            {
                var ret = await queue.ReadAsync(cts.Token);

                Interlocked.Decrement(ref RankMatchmaking.MatchCount);

                ServerCommon.GameResult reply = JsonConvert.DeserializeObject <ServerCommon.GameResult>(ret.Message);

                Log.Information($"game result {ret.Message.ToString()}");

                int total_win_medal    = 0;
                int total_lose_medal   = 0;
                int total_draw_medal   = 0;
                int total_mvp_medal    = 0;
                int total_rankup_medal = 0;
                await Match.RemoveMatch(reply.match_id);

                var characterNames  = new List <string>();
                var characterLevels = new List <int>();


                foreach (var player in reply.player_result)
                {
                    if (player.Value.IsLeave)
                    {
                        continue;
                    }

                    var last_session = await Session.GetSession(player.Key, false);

                    if (last_session != null)
                    {
                        bool is_changed_character_rank_level = false;
                        await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{last_session.session_id}"))
                        {
                            await using (var user = await UserCache.GetUser(last_session.member_no, last_session.user_no, true, true, true))
                                await using (var character = await CharacterCache.Instance.GetEntity(last_session.member_no, last_session.character_no, true, true, true))
                                {
                                    user.play_point += player.Value.play_point;
                                    var last_account_battle_score = user.battle_score;
                                    UserGrowth.IncreaseBattleScore(user, player.Value.battle_point);
                                    var last_battle_score = character.battle_score;
                                    var last_rank_level   = character.rank_level;
                                    CharacterGrowth.IncreaseBattleScore(character, player.Value.battle_point);

                                    var(abs, cbs, wc) = await Ranking.Update(last_session, reply.season_no, player.Value.battle_point, player.Value.IsWin);

                                    bool is_character_rank_level_up = false;
                                    if (last_rank_level != character.rank_level)
                                    {
                                        if (last_rank_level < character.rank_level)
                                        {
                                            is_character_rank_level_up = true;
                                        }
                                    }

                                    if (last_battle_score != character.battle_score)
                                    {
                                        var rankData = ACDC.RankData.GetRank(character.battle_score);
                                        if (rankData != null)
                                        {
                                            if (last_session.rank != rankData.Rank)
                                            {
                                                is_changed_character_rank_level = true;
                                                last_session.rank = rankData.Rank;
                                            }
                                        }
                                    }

                                    var last_medal  = user.medal;
                                    var medal_count = Medal.CalcMedal(user, last_session, reply.is_draw, player.Value, is_character_rank_level_up, game_mode, ref total_win_medal, ref total_lose_medal, ref total_draw_medal, ref total_mvp_medal, ref total_rankup_medal);
                                    await Inventory.Insert(last_session, user, character, (int)GameItemId.Medal, medal_count, null);


                                    // 배틀에서 넘어온 미션 데이터가 없는 경우 초기화
                                    if (player.Value.missions == null)
                                    {
                                        player.Value.missions = new Dictionary <int, int>();
                                    }
                                    player.Value.missions.Increment((int)MissionType.Mission_GetMedal, medal_count);

                                    await MissionManager.Progress(last_session, player.Value.missions);

                                    History.Info(last_session.member_no, last_session.user_no, last_session.character_no, HistoryLogAction.GainAccountBattleScore, (byte)HistoryLogReason.GameResultReward, (int)user.battle_score, (int)last_account_battle_score, reply.match_id.ToString(), "");
                                    History.Info(last_session.member_no, last_session.user_no, last_session.character_no, HistoryLogAction.GainCharacterBattleScore, (byte)HistoryLogReason.GameResultReward, (int)character.battle_score, (int)last_battle_score, reply.match_id.ToString(), "");

                                    characterNames.Add(last_session.user_name);
                                    characterLevels.Add(character.rank_level);
                                }
                        }

                        //Log.Information($"session:{last_session.session_id}, rank:{last_session.rank}");
                        if (is_changed_character_rank_level)
                        {
                            await Session.UpdateSessionLock(last_session.session_id, delegate(Session s) { s.rank = last_session.rank; });
                        }


                        // 게임 종료 이후 매칭 정보 삭제
                        await MatchUser.RemoveMatchUser(last_session.user_no);
                    }
                    else
                    {
                        Log.Warning($"game result lost session:{player.Key}, msg:{ret.Message}");
                    }
                }

                MatchLog.Info(reply, total_win_medal, total_lose_medal, total_draw_medal, total_mvp_medal, total_rankup_medal);

                string resultTp;
                if (reply.is_draw)
                {
                    resultTp = "26";
                    _        = LogProxy.writeActionLog(session, "플레이", "무승부", map_data.ID.ToString()).ConfigureAwait(false);
                }
                else if (reply.statistics.clear == 1)
                {
                    resultTp = "21";
                    _        = LogProxy.writeActionLog(session, "플레이", "클리어", map_data.ID.ToString()).ConfigureAwait(false);
                }
                else
                {
                    resultTp = "22";
                }

                _ = LogProxy.writeRoundLog(session, game_mode.Name, "", "", resultTp, 0, reply.statistics.start_time, reply.statistics.end_time, characterNames, characterLevels, "").ConfigureAwait(false);


                if (reply.statistics.leave_player > 0)
                {
                    _ = LogProxy.writeActionLog(session, "플레이", "이탈", map_data.ID.ToString(), reply.statistics.leave_player.ToString()).ConfigureAwait(false);
                }

                if (reply.statistics.normal_item > 0)
                {
                    _ = LogProxy.writeActionLog(session, "플레이", "일반아이템획득", map_data.ID.ToString(), reply.statistics.normal_item.ToString()).ConfigureAwait(false);
                }

                if (reply.statistics.tactic_item > 0)
                {
                    _ = LogProxy.writeActionLog(session, "플레이", "전략아이템획득", map_data.ID.ToString(), reply.statistics.tactic_item.ToString()).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException ex)
            {
                Log.Information($"game result timeout {ex.ToString()}");
            }
        }
        public static async Task StartPlay(StartPlayRequest request, IServerStreamWriter <StartPlayReply> responseStream, ServerCallContext context)
        {
            var mapData = ACDC.MapData[request.MapId];

            if (mapData == null)
            {
                Log.Warning($"StartPlay error map id {request.MapId}");
                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code = ErrorCode.WrongParam
                });

                return;
            }

            var gameModeData = ACDC.GameModeData[mapData.GameMode];

            if (gameModeData == null)
            {
                Log.Warning($"StartPlay error mode {mapData.GameMode}");
                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code = ErrorCode.WrongParam
                });

                return;
            }

            MinimumStartPlay minimumStartPlay;

            minimumStartPlayMap.TryGetValue(request.MapId, out minimumStartPlay);

            var session = await context.GetSession();

            if (session == null)
            {
                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            Log.Information($"StartPlay user_no:{session.user_no}, user_name:{session.user_name}, mapId:{request.MapId}, SelectedCharacter:{request.SelectedCharacter}, IsImmediatelyJoin{request.IsImmediatelyJoin}");

            bool checkSelectCharacter = await session.SelectCharacter(request.SelectedCharacter);

            if (checkSelectCharacter == false)
            {
                Log.Warning($"StartPlay error character id {request.SelectedCharacter}");
                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code = ErrorCode.WrongParam
                });

                return;
            }

            bool IsAISwitch     = false;
            bool IsFirstRequest = false;
            bool IsWaitingUser  = await WaitingList.IsWaitingUser(session.user_no);

            bool IsMatchTimeout = false;

            // 이미 대기중이 였지만 요청이 달라진 경우,  최초 요청으로 판단
            if (IsWaitingUser == false || session.IsChangeRequest(request))
            {
                IsFirstRequest = true;
                History.Info(session.member_no, session.user_no, session.character_no, HistoryLogAction.TryStartPlay, (byte)HistoryLogReason.None, request.SelectedCharacter, request.MapId, "", "");
                _ = LogProxy.writeActionLog(session, "플레이", "매칭시도", request.MapId.ToString()).ConfigureAwait(false);
            }
            else
            {
                if (DateTime.UtcNow > session.first_request_time.AddMilliseconds(ServerConfiguration.Instance.gameSetting.AIMatchTime))
                {
                    IsMatchTimeout = true;
                    if (ServerConfiguration.Instance.gameSetting.EnableAIMatch == true)
                    {
                        IsAISwitch = true;
                    }
                }

                if (minimumStartPlay != null &&
                    minimumStartPlay.Enable &&
                    DateTime.UtcNow > session.first_request_time.AddSeconds(minimumStartPlay.Timeout))
                {
                    Log.Information($"matchTimeout first_request_time:{session.first_request_time}, now:{DateTime.UtcNow}, timeout:{session.first_request_time.AddSeconds(minimumStartPlay.Timeout)}");
                    IsMatchTimeout = true;
                }
            }

            Log.Information($"flag IsAISwitch:{IsAISwitch}, IsFirstRequest:{IsFirstRequest}, IsWaitingUser{IsWaitingUser}, IsMatchTimeout{IsMatchTimeout}");


            if (request.SelectedCharacter != session.character_type || request.MapId != session.map_id)
            {
                var user = await UserCache.GetUser(session.member_no, session.user_no, false);

                user.character_no = session.character_no;
                user.map_id       = (byte)request.MapId;
                user.IsDirty      = true;
            }

            // 게임 시작 요청 정보를 캐싱
            await session.UpdateSessionLock(request.SelectedCharacter, request.MapId, IsFirstRequest);

            if (request.IsImmediatelyJoin)
            {
                await StartPlaySimulate(request, responseStream, context, session, mapData, gameModeData);

                return;
            }

            long match_id = await MatchInstanceId.GetMatchInstanceId();

            if ((await MatchUser.OccupyMatchUser(session.user_no, match_id)) == false)
            {
                // 다른 플레이어로 인해 매칭이 완료 되었는지 확인
                if ((await RestoreMatchUser(session, responseStream)) == true)
                {
                    if (ServerConfiguration.Instance.gameSetting.EnableReJoin == false)
                    {
                        // 재입장이 불가하면, 게임 시작 직후 매칭 정보 삭제
                        await MatchUser.RemoveMatchUser(session.user_no);
                    }
                    return;
                }
                else
                {
                    await responseStream.WriteAsync(new StartPlayReply()
                    {
                        Code             = ErrorCode.NotEnough,
                        IsStart          = false,
                        BattleServerAddr = "",
                        WorldId          = 0,
                        MapId            = request.MapId,
                    });

                    return;
                }
            }

            if (request.IsCancel)
            {
                // 대기 목록에서 제거
                await WaitingList.RemoveWaitingUser(session.user_no);

                await MatchUser.RemoveMatchUser(session.user_no);


                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code             = ErrorCode.NotEnough,
                    IsStart          = false,
                    BattleServerAddr = "",
                    WorldId          = 0,
                    MapId            = request.MapId,
                });

                return;
            }

            // 대기중이 플레이어 찾기
            (var matchResult, var search_success) = await SearchPlayer(session, match_id, mapData, gameModeData);

            if (search_success == false && IsAISwitch == true)
            {
                // 부족한 인원 만큼 AI로 채워 넣는다.(자신은 제외)
                int cnt = (GetStartPlayerCount(gameModeData) - 1) - matchResult.replyToClient.CharacterList.Count;
                for (int i = 0; i < cnt; ++i)
                {
                    matchResult.AddAI(session, mapData, gameModeData);
                }
            }

            if (search_success == true || IsAISwitch == true ||
                (ServerConfiguration.Instance.gameSetting.MatchForce && IsMatchTimeout) ||
                (minimumStartPlay != null && minimumStartPlay.Enable && IsMatchTimeout && matchResult.replyToClient.CharacterList.Count + 1 >= minimumStartPlay.PlayerCount)
                )
            {
                // 게임 시작
                if ((await StartPlay(match_id, session, request, responseStream, matchResult, mapData, gameModeData)) == false)
                {
                    // 예약했던 플레이어 취소
                    await MatchUser.CancelOccupiedMatchUser(matchResult.replyToBattleServer.players);
                }
                else
                {
                    if (ServerConfiguration.Instance.gameSetting.EnableReJoin == false)
                    {
                        // 재입장이 불가하면, 게임 시작 직후 매칭 정보 삭제
                        await MatchUser.RemoveMatchUser(session.user_no);
                    }
                }
                return;
            }

            // 예약했던 플레이어 취소
            await MatchUser.CancelOccupiedMatchUser(matchResult.replyToBattleServer.players);

            Log.Information("StartPlay waiting... {0}", session.user_no);

            // 대기
            await WaitStartPlay(session, request, responseStream);

            // 검색 실패시 다음 검색 조건 범위를 넓힌다.
            await session.WideningRangeRankLock();

            // 실패 결과 리턴
            matchResult.replyToClient.Code    = ErrorCode.NotEnough;
            matchResult.replyToClient.IsStart = false;
            matchResult.replyToClient.CharacterList.Add(new StartPlayCharacterInfo()); // 자신포함으로 빈슬롯 한개 넣어줌
            await responseStream.WriteAsync(matchResult.replyToClient);
        }