Exemple #1
0
        public UserModule(ITokenizer tokenizer)
            : base("/user")
        {
            // 가입
            // 이메일, 비밀번호,
            Post["/signup"] = parameters =>
            {
                string userId     = Request.Form.userId;
                string password   = Request.Form.password;
                string playerName = Request.Form.playername;

                // if ( AccountInfoDatabase.SetAccountInfo( new AccountInfo( userId, password ) ) )
                var task = PostgresqlManager.SetAccountInfo(userId, password);
                task.Wait();

                Console.WriteLine("finished PostgreSQL job");

                // if (task.Result)
                {
                    // user identity
                    // UserIdentityDatabase.SetUserIdentity( new UserIdentity { UserName = userId, Claims = new List<string> { "user", } } );

                    // user data
                    bool result = UserDataDatabase.SetUserData(new UserData {
                        UserId    = userId,
                        Gold      = 0,
                        Inventory = new List <uint> {
                        },
                        Token     = new List <ItemToken> {
                        },
                        BanList   = new List <string> {
                        },
                    });
                    if (!result)
                    {
                        return("fail");
                    }
                    Console.WriteLine("created user data");

                    // player data
                    result = PlayerDataDatabase.SetPlayerData(new PlayerData
                    {
                        pId    = userId,
                        name   = playerName,
                        exp    = 0,
                        stats  = new ushort[] { 1, 5, 5, 5, 5, 5, 5, 5, },
                        skills = new List <SkillId> {
                            SkillId.Punch,
                        },
                        consumables = new List <ItemCode> {
                            ItemCode.HpPotion_S,
                        },
                        equipments = new List <ItemCode> {
                            ItemCode.Sword_Test,
                        },
                        battleStyle = BattleStyle.AGGRESSIVE,
                    });
                    if (!result)
                    {
                        return("fail");
                    }
                    Console.WriteLine("created player data");

                    // result table
                    result = ResultTableDatabase.SetResultTable(new ResultTable
                    {
                        PlayerId = userId,
                        ReadId   = new List <long> {
                        },
                        UnreadId = -1
                    });
                    if (!result)
                    {
                        return("fail");
                    }
                    Console.WriteLine("created result table");

                    // ranking list
                    RedisManager.RegisterPlayerRank(userId);

                    return("success");
                }
            };

            // 로그인
            // 이메일과 비밀번호를 전송받아서
            // 저장된 값과 비교해보고
            // 같으면 쿠키 발급
            Post["/login"] = parameters =>
            {
                var userName = (string)this.Request.Form.UserName;
                var password = (string)this.Request.Form.Password;

                // var userIdentity = UserIdentityDatabase.ValidateUser( userName, password );
                var task = PostgresqlManager.ValidateUser(userName, password);
                task.Wait();
                var userIdentity = task.Result;

                if (userIdentity == null)
                {
                    return(HttpStatusCode.Unauthorized);
                }

                var token = tokenizer.Tokenize(userIdentity, Context);

                Console.WriteLine(userName + " : " + token);

                return(new
                {
                    Token = token,
                });
            };

            // 탈퇴
            // 는 없다.

            // 로그인 상태 확인
            Get["/valid_session"] = parameters =>
            {
                this.RequiresAuthentication();

                return("valid");
            };
        }
Exemple #2
0
        public CharacterModule(ITokenizer tokenizer)
            : base("/character")
        {
            // 시뮬레이션 결과 요청
            Get["/simulation_result"] = parameters =>
            {
                // 일단 해당 유저의 id를 확인하고, 시뮬레이션 결과가 있는지 확인한다
                this.RequiresAuthentication();

                var resultTable = ResultTableDatabase.GetResultTable(this.Context.CurrentUser.UserName);

                if (resultTable == null || resultTable.UnreadId == -1)
                {
                    return("nothing");
                }

                // 해당 시뮬레이션 데이터를 가져온다
                var result = SimulationResultDatabase.GetSimulationResult(resultTable.UnreadId);

                if (resultTable == null)
                {
                    return("error");     // 조심해! 이거 500이나 뭐 그런 걸로 핸들링할까?
                }
                // 시뮬레이션 결과 베이스 데이터를 구성한다
                GameResultBaseData baseData = new GameResultBaseData();
                baseData.mapSize    = result.MapSize;
                baseData.randomSeed = result.Seed;
                baseData.partyLevel = result.PartyLevel;

                result.PlayerList.ForEach(each => baseData.playerList.Add(each));

                // 읽은 애들은 삭제하자
                // 일단은 놔둠
                resultTable.ReadId.Add(resultTable.UnreadId);
                resultTable.UnreadId = -1;   // default value

                Debug.Assert(ResultTableDatabase.SetResultTable(resultTable));

                // 전송한다
                return(JsonConvert.SerializeObject(baseData));;
            };

            Get["/update"] = parameters =>
            {
                // 캐릭터의 최신 정보 받기

                /*
                 * Console.WriteLine("update");
                 * foreach ( var each in this.Context.Request.Headers )
                 * {
                 *  Console.WriteLine( each.Key + ": " );
                 *  foreach ( var item in each.Value )
                 *      Console.WriteLine( item );
                 * }
                 */
                // 일단 해당 유저의 id를 확인하고
                this.RequiresAuthentication();

                PlayerData playerData = PlayerDataDatabase.GetPlayerData(this.Context.CurrentUser.UserName);
                UserData   userData   = UserDataDatabase.GetUserData(this.Context.CurrentUser.UserName);

                return(JsonConvert.SerializeObject(new ClientPlayerData(playerData, userData)));;
            };

            Get["/levelup"] = parameters =>
            {
                try
                {
                    // 일단 해당 유저의 id를 확인하고
                    this.RequiresAuthentication();

                    PlayerData playerData = PlayerDataDatabase.GetPlayerData(this.Context.CurrentUser.UserName);

                    Debug.Assert(playerData != null);

                    Player player = new Player();
                    player.LoadPlayer(playerData);

                    if (player.LevelUp(1))
                    {
                        // update playerData
                        playerData.UpdateFromPlayer(player);

                        Debug.Assert(PlayerDataDatabase.SetPlayerData(playerData));

                        return("levelup");
                    }

                    return("need more exp");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                return("fail");
            };

            Post["/increase_stat"] = parameters =>
            {
                // 일단 해당 유저의 id를 확인하고
                this.RequiresAuthentication();

                PlayerData playerData = PlayerDataDatabase.GetPlayerData(this.Context.CurrentUser.UserName);

                Player player = new Player();
                player.LoadPlayer(playerData);

                ushort[] request = JsonConvert.DeserializeObject <ushort[]>(this.Request.Form.stat);
                List <Tuple <StatType, ushort> > requestStats = new List <Tuple <StatType, ushort> >();

                for (int i = (int)StatType.Str; i < (int)StatType.Mov; ++i)
                {
                    if (request[i] != 0)
                    {
                        requestStats.Add(new Tuple <StatType, ushort>((StatType)i, request[i]));
                    }
                }

                if (player.SetBonusStats(requestStats))
                {
                    // update playerData
                    playerData.UpdateFromPlayer(player);

                    Debug.Assert(PlayerDataDatabase.SetPlayerData(playerData));

                    return("stats changed");
                }

                return("failed");
            };

            Get["/rank"] = parameters =>
            {
                // 일단 해당 유저의 id를 확인하고
                this.RequiresAuthentication();

                long rank = RedisManager.GetRank(this.Context.CurrentUser.UserName);

                return(rank);
            };
        }
        public static void Simulation(Party party)
        {
            var runningTime = Stopwatch.StartNew();

            Debug.WriteLine("start to simulation");
            Console.WriteLine("start to simulation");

            party.characters.ForEach(each => Console.WriteLine("equip : " + each.equipments.Count));

            SimulationResult result = new SimulationResult();

            long currentIdx = Interlocked.Increment(ref resultIdx);

            // over flow 확인하고 제어 할 것

            result.Id         = currentIdx;
            result.PartyLevel = party.partyLevel;
            result.Seed       = random.Next();
            result.MapSize    = 60;

            // result에 사용될 사용자 정보 기록
            result.PlayerList = new List <PlayerData>();
            party.characters.ForEach(each =>
            {
                var player = (Player)each;
                result.PlayerList.Add(player.ConvertToPlayerData());
            });

            Console.WriteLine("party level : " + party.partyLevel);

            // simulation!!!!
            DungeonMaster newMaster = new DungeonMaster();

            newMaster.Init(result.MapSize, result.Seed, party);
            var res = newMaster.Start();

            Console.WriteLine("turn : " + res);
            Console.WriteLine("looted gold : " + newMaster.record.lootedGold);
            Console.WriteLine("looted exp : " + newMaster.record.lootedExp);

            // save the result data in DB
            result.CheckedPlayer = new List <ulong>();
            Debug.Assert(SimulationResultDatabase.SetSimulationResult(result));

            party.characters.ForEach(each =>
            {
                string id = ((Player)each).pId;

                // update player data
                var playerData = PlayerDataDatabase.GetPlayerData(id);
                var userData   = UserDataDatabase.GetUserData(id);

                // 크게 할 일은 경험치 추가, 골드 추가, 아이템토큰 추가
                userData.Gold  += newMaster.record.lootedGold;
                playerData.exp += newMaster.record.lootedExp;
                newMaster.record.lootedItems.ForEach(eachItem => { userData.Token.Add((ItemToken)eachItem); });

                Debug.Assert(UserDataDatabase.SetUserData(userData));
                Debug.Assert(PlayerDataDatabase.SetPlayerData(playerData));

                // update result table
                var resultTable = ResultTableDatabase.GetResultTable(id);
                Debug.Assert(resultTable.UnreadId == -1, "unread result remains");

                resultTable.UnreadId = currentIdx;
                Debug.Assert(ResultTableDatabase.SetResultTable(resultTable), "fail to save the result table - ID : " + resultTable.PlayerId);

                // update rank
                RedisManager.UpdateRank(playerData.pId, playerData.GetScore());
            });

            Debug.WriteLine("simulation ended");
            Console.WriteLine("simulation ended");

            LogRecord.Write("[Simulation : " + runningTime.ElapsedMilliseconds + " ms]");
        }