예제 #1
0
        public static void RankingPlayer_Test()
        {
            List <Player> playerList = PlayerDb.GetRankingPlayerListWithLimit(3);

            Assert.AreEqual(playerList.Count, 3);

            //var player1 = new List<string>() { "", "0", "0", "0" };
            //var player2 = new List<string>() { "Ty", "3", "5", "2" };
            //var player3 = new List<string>() { "Suu", "13", "4", "4" };
            var player4 = new List <string>()
            {
                "Dan", "13", "5", "1"
            };
            var player5 = new List <string>()
            {
                "Meo", "14", "3", "3"
            };
            //var player6 = new List<string>() { "Thin", "2", "34", ""39" };
            var player7 = new List <string>()
            {
                "Ty", "17", "0", "0"
            };

            Assert.AreEqual(RankingPlayer(playerList[0]), player7);
            Assert.AreEqual(RankingPlayer(playerList[1]), player5);
            Assert.AreEqual(RankingPlayer(playerList[2]), player4);
            //Assert.AreEqual(RankingPlayer(playerList[3]), player3);
            //Assert.AreEqual(RankingPlayer(playerList[4]), player2);
            //Assert.AreEqual(RankingPlayer(playerList[5]), player6);
            //Assert.AreEqual(RankingPlayer(playerList[6]), player1);
        }
예제 #2
0
        public async Task <Player> GetPlayer(long id, bool onlineOnly = false)
        {
            if (ContainsKey(id))
            {
                TryGetValue(id, out var value);
                return(value);
            }

            if (onlineOnly)
            {
                return(null);
            }

            if (!Redis.IsConnected)
            {
                return(await PlayerDb.Get(id));
            }

            var player = await Redis.GetCachedPlayer(id);

            if (player != null)
            {
                return(player);
            }

            player = await PlayerDb.Get(id);

            await Redis.CachePlayer(player);

            return(player);
        }
예제 #3
0
        public static void Construct()
        {
            Configuration = new Configuration();
            Configuration.Initialize();

            _logger = new Logger();

            Logger.Log($"ENV: {(Utils.IsLinux ? "Linux" : "Windows")}");

            Csv         = new Csv();
            Fingerprint = new Fingerprint();

            _playerDb   = new PlayerDb();
            _replayDb   = new ReplayDb();
            _allianceDb = new AllianceDb();

            _redis = new Redis();

            Levels           = new Levels();
            PlayerCache      = new Players();
            AllianceCache    = new Alliances();
            LeaderboardCache = new Leaderboards();

            ChatManager = new LogicGlobalChatManager();

            Gateway = new Gateway();

            StartDateTime = DateTime.UtcNow;

            Gateway.StartAsync().Wait();
        }
예제 #4
0
파일: Bl.cs 프로젝트: samuelarbibe/taki
        public void BlSwitchHands(Message m)
        {
            PlayerCardDb db       = new PlayerCardDb();
            PlayerDb     playerDb = new PlayerDb();

            db.SwitchConnectionsByPlayersId(m.Target, playerDb.GetPlayerById(m.Card.Id));
        }
예제 #5
0
        public async Task <bool> RemovePlayer(long id, Guid sessionId)
        {
            try
            {
                if (!ContainsKey(id))
                {
                    return(true);
                }

                var player = this[id];

                player.Timer.Stop();

                if (Redis.IsConnected)
                {
                    await Redis.CachePlayer(player);
                }

                await PlayerDb.Save(player);

                return(player.Device.SessionId == sessionId && TryRemove(id, out var _));
            }
            catch (Exception exception)
            {
                Logger.Log(exception, Enums.LogType.Error);
                return(false);
            }
        }
예제 #6
0
        public static async void Initialize()
        {
            Logger = new Logger();
            Logger.Log(
                $"Starting [{DateTime.Now.ToLongTimeString()} - {ServerUtils.GetOsName()}]...",
                null);

            Configuration = new Configuration();
            Configuration.Initialize();

            Fingerprint = new Fingerprint();
            Levels      = new Levels();
            Csv         = new Csv();

            PlayerDb = new PlayerDb();
            //AllianceDb = new AllianceDb();

            Logger.Log(
                $"Successfully loaded MySql with {await PlayerDb.CountAsync()} player(s)",
                null);

            ObjectCache = new ObjectCache();

            Players = new Players();
            //Alliances = new Alliances();

            //Leaderboard = new Leaderboard();

            StartTime = DateTime.UtcNow;

            Netty = new NettyService();

            await Task.Run(Netty.RunServerAsync);
        }
예제 #7
0
        /// <summary>
        ///     Get a player from cache or database
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="onlineOnly"></param>
        /// <returns></returns>
        public async Task <Player> GetPlayerAsync(long userId, bool onlineOnly = false)
        {
            lock (SyncObject)
            {
                if (ContainsKey(userId))
                {
                    return(this[userId]);
                }
            }

            if (onlineOnly)
            {
                return(null);
            }

            var player = Resources.ObjectCache.GetCachedPlayer(userId);

            if (player != null)
            {
                return(player);
            }

            player = await PlayerDb.GetAsync(userId);

            Resources.ObjectCache.CachePlayer(player);

            return(player);
        }
예제 #8
0
        /// <summary>
        ///     Get a player from cache or database
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="onlineOnly"></param>
        /// <returns></returns>
        public async Task <Player> GetPlayerAsync(long userId, bool onlineOnly = false)
        {
            lock (SyncObject)
            {
                if (ContainsKey(userId))
                {
                    return(this[userId]);
                }
            }

            if (onlineOnly)
            {
                return(null);
            }

            if (!Redis.IsConnected)
            {
                return(await PlayerDb.GetAsync(userId));
            }

            var player = await Redis.GetPlayerAsync(userId);

            if (player != null)
            {
                return(player);
            }

            player = await PlayerDb.GetAsync(userId);

            await Redis.CacheAsync(player);

            return(player);
        }
예제 #9
0
        public async void TimerCallback(object state, ElapsedEventArgs args)
        {
            await Task.Run(async() =>
            {
                try
                {
                    var currentGlobalPlayerRanking = await PlayerDb.GetGlobalPlayerRanking();
                    for (var i = 0; i < currentGlobalPlayerRanking.Count; i++)
                    {
                        GlobalPlayers.UpdateOrInsert(i, currentGlobalPlayerRanking[i]);
                    }

                    foreach (var players in LocalPlayers)
                    {
                        var currentLocalPlayerRanking = await PlayerDb.GetLocalPlayerRanking(players.Key);
                        for (var i = 0; i < currentLocalPlayerRanking.Count; i++)
                        {
                            players.Value.UpdateOrInsert(i, currentLocalPlayerRanking[i]);
                        }
                    }
                }
                catch (Exception exception)
                {
                    Logger.Log(exception, Enums.LogType.Error);
                }
            });
        }
예제 #10
0
        public async Task <bool> RemovePlayer(long id, Guid sessionId, bool force = false)
        {
            try
            {
                if (!ContainsKey(id))
                {
                    return(true);
                }

                var player = this[id];

                await PlayerDb.Save(player);

                if (force)
                {
                    return(TryRemove(id, out var _));
                }

                return(player.Device.SessionId == sessionId && TryRemove(id, out var _));
            }
            catch (Exception exception)
            {
                Logger.Log(exception, Enums.LogType.Error);
                return(false);
            }
        }
예제 #11
0
        public async void Tick(object state, ElapsedEventArgs args)
        {
            await Task.Run(async() =>
            {
                try
                {
                    var currentGlobalPlayerRanking = await PlayerDb.GetGlobalPlayerRankingAsync();
                    for (var i = 0; i < currentGlobalPlayerRanking.Count; i++)
                    {
                        GlobalPlayerRanking.UpdateOrInsert(i, currentGlobalPlayerRanking[i]);
                    }

                    foreach (var(key, value) in LocalPlayerRanking)
                    {
                        var currentLocalPlayerRanking = await PlayerDb.GetLocalPlayerRankingAsync(key);
                        for (var i = 0; i < currentLocalPlayerRanking.Count; i++)
                        {
                            value.UpdateOrInsert(i, currentLocalPlayerRanking[i]);
                        }
                    }
                }
                catch (Exception exception)
                {
                    Logger.Log($"Error while updating leaderboads {exception}", GetType(), ErrorLevel.Error);
                }
            });
        }
예제 #12
0
        public static async void Initialize()
        {
            Logger = new Logger();
            Logger.Log(
                $"Starting [{DateTime.Now.ToLongTimeString()} - {ServerUtils.GetOSName()}]...",
                null);

            Configuration = new Configuration();
            Configuration.Initialize();

            Fingerprint = new Fingerprint();
            Sentry      = new SentryReport();
            Csv         = new Csv();

            UpdateManager = new UpdateManager();

            PlayerDb   = new PlayerDb();
            AllianceDb = new AllianceDb();

            Logger.Log(
                $"Successfully loaded MySql with {await PlayerDb.CountAsync()} player(s) & {await AllianceDb.CountAsync()} clan(s)",
                null);

            Redis = new Redis();

            Battles   = new Battles();
            Players   = new Players();
            Alliances = new Alliances();

            Leaderboard = new Leaderboard();

            Netty = new NettyService();

            await Task.Run(Netty.RunServerAsync);
        }
예제 #13
0
        private void BtnCreatAccount_Click(object sender, RoutedEventArgs e)
        {
            //Verify if this login already exists in database
            List <Player> allPlayer = PlayerDb.GetAllPlayer();
            var           player1   = allPlayer.FirstOrDefault(s => s.Pseudo == txbPeuso.Text);

            if (player1 != null)
            {
                MessageBox.Show("Ce pseudo existe déjà, choissez un autre :");
                this.Hide();
                SignUp signUp = new SignUp();
                signUp.ShowDialog();
            }
            else
            {
                if (txbPasswordConfirmed.Password == txbPassword.Password)
                {
                    this.Hide();
                    PlayerDb.InsertPlayer(txbPeuso.Text, txbPassword.Password, txbFullName.Text); //Insert player to database
                    Services.GetPlayer(txbPeuso.Text, txbPassword.Password);                      //Immediately get player

                    Home click = new Home();
                    click.ShowDialog();
                }
                else
                {
                    MessageBox.Show("Le mot de passe confirmé n'est pas correct");
                }
            }
        }
예제 #14
0
 void Update()
 {
     if (SceneManager.sceneCount > 1)
     {
         GetComponent <player>().Load();
         playerDb = GetComponent <player>().Player;
     }
 }
예제 #15
0
        public ActionResult GetPlayer()
        {
            db = new PlayerDb();

            List <Player> listPlayers = new List <Player>();

            listPlayers = db.GetPlayers();
            return(View(listPlayers));
        }
예제 #16
0
        public void EndGame()
        {
            List <Token> tokensBackToPlayer1 = new List <Token>();
            List <Token> tokensBackToPlayer2 = new List <Token>();

            for (int i = 1; i < 6; i++)
            {
                tokensBackToPlayer1 = board.PlayersList[0].EatTokensInSquare(board.SquaresList[i]);
                tokensBackToPlayer2 = board.PlayersList[1].EatTokensInSquare(board.SquaresList[i + 6]);
            }
            UpdateEllipsesInBoard();//to remove ellipses in row
            AddEllipsesInPool(1, tokensBackToPlayer1);
            AddEllipsesInPool(2, tokensBackToPlayer2);
            Services.Player.UpdateResult(board);
            PlayerDb.UpdatePlayerDb(Services.Player);

            var declarationGameResult = "";

            switch (board.GetResult())
            {
            case Result.WIN:
                declarationGameResult = Services.Player.Pseudo + " a gagné";
                break;

            case Result.LOSE:
                declarationGameResult = board.PlayersList[1].Pseudo + " a gagné";
                break;

            case Result.DRAW:
                declarationGameResult = "Partie nulle";
                break;
            }

            MessageBoxResult result = MessageBox.Show(board.PlayersList[0].Pseudo + " a " + board.PlayersList[0].Score + " points\n"
                                                      + board.PlayersList[1].Pseudo + " a " + board.PlayersList[1].Score + " points\n"
                                                      + "\n" + declarationGameResult.ToUpper()
                                                      + "\nVous voulez rejouer ?",
                                                      "Résultat",
                                                      MessageBoxButton.YesNo,
                                                      MessageBoxImage.Question,
                                                      MessageBoxResult.No);

            switch (result)
            {
            case MessageBoxResult.Yes:
                this.Close();
                Services.NoveltyOfGame = NoveltyOfGame.NEW;
                PlayGame game = new PlayGame();
                game.ShowDialog();
                break;

            case MessageBoxResult.No:
                this.Close();
                break;
            }
        }
예제 #17
0
        public ActionResult Login(Player player)
        {
            db = new PlayerDb();

            List <Player> listPlayers = new List <Player>();

            listPlayers = db.GetPlayers();

            var korisnik = listPlayers.Exists(x => x.KorisnickoIme.Equals(player.KorisnickoIme) && listPlayers.Exists(y => y.Lozinka.Equals(player.Lozinka)));



            if (korisnik)
            {
                Session["korisnik"] = player.KorisnickoIme;

                return(View("LoginSuccess"));
            }

            return(View());



            // db = player.KorisnickoIme.Any(korisnickoIme));
            //var user = IsUserNameAvailable(korisnickoIme);

            //Session["korisnik"] = player.KorisnickoIme;
            //return RedirectToAction("LoginSuccess", user);



            //List<Player> players = db.GetPlayers();

            //if (players.Any(x => x.KorisnickoIme != null))
            //{
            //    return View(players);
            //}



            //var userdetail = db.GetPlayers();
            //if (!userdetail.Exists(x=>x.KorisnickoIme))
            //{
            //    Session["korisnik"] = player.KorisnickoIme;
            //    return View("LoginSuccess");



            //var newUser = db.CheckRecord(player);

            //if (newUser)
            //{
            //    Session["korisnik"] = player.KorisnickoIme;
            //    return View("LoginSuccess");
            //}
        }
예제 #18
0
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            //save the enter info into the properties of object ThisPlayer
            ThisPlayer.FullName  = txbFullName.Text;
            ThisPlayer.IsEnabled = (cobEnabled.Text == "Oui") ? 1 : 0;
            ThisPlayer.IsAdmin   = (cobAdmin.Text == "Oui") ? 1 : 0;

            PlayerDb.UpdatePlayerDb(ThisPlayer);                              //to save player with new info in database
            PlayerInfo.dataGrid.ItemsSource = Services.PlayerListWithRanking; //reload the playerlist from database
            MessageBox.Show("Enregistré !");
        }
예제 #19
0
 private void ReactivatePlayer(long playerId)
 {
     if (IsAdmin == 1)
     {
         PlayerDb.ReactivatePlayer(playerId);
     }
     else
     {
         throw new ArgumentOutOfRangeException(nameof(PlayerId), "Cette fonctionnalité n'est réservée qu'au administrateur");
     }
 }
예제 #20
0
        /// <summary>
        ///     Login a player
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        public async Task <Player> Login(long userId, string token)
        {
            Player player;

            if (userId <= 0 && string.IsNullOrEmpty(token))
            {
                player = await PlayerDb.CreateAsync();
            }
            else
            {
                //var p = await Redis.GetPlayerAsync(userId);
                var p = Resources.ObjectCache.GetCachedPlayer(userId);

                if (p != null)
                {
                    player = p;
                }
                else
                {
                    player = await PlayerDb.GetAsync(userId);
                }

                if (player == null)
                {
                    return(null);
                }
                if (player.Home.UserToken != token)
                {
                    return(null);
                }
            }

            lock (SyncObject)
            {
                if (player == null)
                {
                    return(null);
                }

                Logout(ref player);

                var result = TryAdd(player.Home.Id, player);

                if (!result)
                {
                    return(null);
                }

                //Logger.Log($"User {player.Home.Id} logged in.", GetType(), ErrorLevel.Debug);

                return(player);
            }
        }
예제 #21
0
 public void Dispose()
 {
     Csv                  = null;
     Gateway              = null;
     PlayerCache          = null;
     Configuration        = null;
     Levels               = null;
     Fingerprint          = null;
     _messagefactory      = null;
     _commandfactory      = null;
     _debugcommandfactory = null;
     _playerDb            = null;
     _replayDb            = null;
     _allianceDb          = null;
     _logger              = null;
 }
예제 #22
0
        public async void Save()
        {
#if DEBUG
            var st = new Stopwatch();
            st.Start();

            Resources.ObjectCache.CachePlayer(this);
            await PlayerDb.SaveAsync(this);

            st.Stop();
            Logger.Log($"Player {Home.Id} saved in {st.ElapsedMilliseconds}ms.", GetType(), ErrorLevel.Debug);
#else
            Resources.ObjectCache.CachePlayer(this);
            await PlayerDb.SaveAsync(this);
#endif
        }
예제 #23
0
        //// <summary>
        /// Get ranking of own player
        /// </summary>
        /// <returns>int</returns>
        public int GetOwnRanking()
        {
            var ownRanking        = 0;
            var count             = PlayerDb.CountPlayer();
            var playerListRanking = PlayerDb.GetRankingPlayerListWithLimit(count);

            for (int i = 0; i < count; i++)
            {
                if (playerListRanking[i].Pseudo == Pseudo)
                {
                    ownRanking = i + 1;
                    break;
                }
            }
            return(ownRanking);
        }
예제 #24
0
        public static void GetAllPlayer_Test()
        {
            List <Player> playerList = PlayerDb.GetAllPlayer();

            Assert.AreEqual(playerList.Count, 8);
            var player1 = new List <string>()
            {
                "", ""
            };
            var player2 = new List <string>()
            {
                "Ti", "Chuot"
            };
            var player3 = new List <string>()
            {
                "Suu", "Trau"
            };
            var player4 = new List <string>()
            {
                "Dan", "Cop"
            };
            var player5 = new List <string>()
            {
                "Meo", "Meo"
            };
            var player6 = new List <string>()
            {
                "Thin", "Rong"
            };
            var player7 = new List <string>()
            {
                "Ty", "Ran"
            };
            var player8 = new List <string>()
            {
                "Ngo", "Ngua"
            };

            Assert.AreEqual(ShowPlayer(playerList[0]), player1);
            Assert.AreEqual(ShowPlayer(playerList[1]), player2);
            Assert.AreEqual(ShowPlayer(playerList[2]), player3);
            Assert.AreEqual(ShowPlayer(playerList[3]), player4);
            Assert.AreEqual(ShowPlayer(playerList[4]), player5);
            Assert.AreEqual(ShowPlayer(playerList[5]), player6);
            Assert.AreEqual(ShowPlayer(playerList[6]), player7);
            Assert.AreEqual(ShowPlayer(playerList[7]), player8);
        }
예제 #25
0
        /// <summary>
        /// Deserializes the specified entity.
        /// </summary>
        public bool Deserialize(PlayerDb PlayerDb, out Player Player)
        {
            if (PlayerDb.Content != null)
            {
                Player = JsonConvert.DeserializeObject <Player>(PlayerDb.Content.ToJson(), GameDb.JsonSettings);

                if (Player != null)
                {
                    return(true);
                }
            }
            else
            {
                Player = null;
            }

            return(false);
        }
예제 #26
0
 void Start()
 {
     GetComponent <player>().Load();
     TimeStatic.realTimeStatic = GetComponent <realtime>().RealTime;
     McPlayer = GetComponent <player>().Player;
     GetData(Energy, 1);
     GetData(Blood, 2);
     GetData(Defense, 3);
     if (TimeStatic.realTimeStatic.TimeBlood == 0)
     {
         Blood.Enable = false;
     }
     if (TimeStatic.realTimeStatic.TimeDefense == 0)
     {
         Defense.Enable = false;
     }
     StartCoroutine("DatabaseUpdate");
 }
예제 #27
0
 private void BtnLogin_Click(object sender, RoutedEventArgs e)
 {
     //Verify if this pseudo already exists
     if (PlayerDb.GetPlayer(txbPeuso.Text, txbPassword.Password) == null)
     {
         MessageBox.Show("Pseudo ou Mot de passe sont incorrect. Réessayez !");
         this.Hide();
         SignIn signIn = new SignIn();
         signIn.ShowDialog();
     }
     else
     {
         Services.GetPlayer(txbPeuso.Text, txbPassword.Password);//Immediately get player
         Home click = new Home();
         MessageBox.Show(click, "Login réussi !");
         this.Hide();
         click.ShowDialog();
     }
 }
예제 #28
0
        public async void Save()
        {
            Home.LastSaveTime = DateTime.UtcNow;

/*#if DEBUG
 *          var st = new Stopwatch();
 *          st.Start();
 *
 *          Resources.ObjectCache.CachePlayer(this);
 *          await PlayerDb.SaveAsync(this);
 *
 *          st.Stop();
 *          Logger.Log($"Player {Home.Id} saved in {st.ElapsedMilliseconds}ms.", GetType(), ErrorLevel.Debug);
 #else*/
            Resources.ObjectCache.CachePlayer(this);
            await PlayerDb.SaveAsync(this);

//#endif
        }
예제 #29
0
        public Home()
        {
            InitializeComponent();

            //Display the best players
            icBestPlayerList.ItemsSource = PlayerDb.GetRankingPlayerListWithLimit(5);
            txbWelcome.Text = "Bienvenu " + Services.Player.Pseudo + " !";

            //Display info of player
            tbiPlayer.DataContext = Services.Player;
            lblOwnRanking.Content = Services.Player.Ranking + "/" + Services.PlayerQty;
            lblIsAdmin.Content    = (Services.Player.IsAdmin == 1) ? "Oui" : "Non";
            lblIsDisabled.Content = (Services.Player.IsEnabled == 1) ? "Oui" : "Non";

            //Administration
            if (Services.Player.IsAdmin != 1)
            {
                btnAdmin.Visibility = Visibility;//Hide this button since player is not admin
            }
        }
예제 #30
0
        public async Task <int> SaveScore(ShapeModel winnerShape)
        {
            using (var db = new PlayerDb())
            {
                var players = from p in db.player select p;

                foreach (var p in players)
                {
                    p.GamesPlayed += 1;
                    if (p.PlayerID == winnerShape.ActivePlayerId)
                    {
                        p.GamesWon += 1;
                    }
                    db.Entry(p).State = System.Data.Entity.EntityState.Modified;
                }
                var i = await db.SaveChangesAsync();

                return(i);
            }
        }