/// <inheritdoc />
        public IPlayer GetOnlinePlayerById(string id)
        {
            IEnumerable <EcoPlayer> players = OnlinePlayers.Cast <EcoPlayer>();

            return(players.FirstOrDefault(x => x.Id.Equals(id))
                   ?? throw new EcoPlayerNotFoundException(id));
        }
Exemple #2
0
        /// <summary>
        /// Verify a user token and login.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>login result</returns>
        public virtual bool LogIn(string username, string password)
        {
            // if already online, deny.
            if (OnlinePlayers.Any(p => p.Username == username))
            {
                return(false);
            }

            if (!PlayerRepository.IsExsist(username))
            {
                return(false);
            }

            Player player = PlayerRepository.GetPlayer(username);

            if (player.Token.ToString() != password)
            {
                return(false);
            }

            OnlinePlayers.Add(player);
            Session.Value.Set(player).Exiting += Session_Exiting;
            LoggedIn?.Invoke(this, player);
            Logger.Info($"[{username}] login succeed");

            return(true);
        }
Exemple #3
0
 public void RemovePlayer(Player player)
 {
     lock (OnlinePlayers)
     {
         OnlinePlayers.Remove(player);
     }
 }
 /// <summary>
 ///     Handle a player disconnect event
 /// </summary>
 private static void HandlePlayerDisconnect(string text, OutputParseResult outputparseresult, IPlayerAction playeraction)
 {
     if (OnlinePlayers.ContainsKey(playeraction.PlayerName))
     {
         OnlinePlayers.Remove(playeraction.PlayerName);
     }
     RaisePlayerListChangedEvent();
 }
        /// <inheritdoc />
        public IPlayer GetOnlinePlayerByName(string name)
        {
            IEnumerable <EcoPlayer> players = OnlinePlayers.Cast <EcoPlayer>();

            return(players.FirstOrDefault(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
                   ?? players.FirstOrDefault(x => x.Name.ComparerContains(name))
                   ?? throw new EcoPlayerNotFoundException(name));
        }
Exemple #6
0
        public Player GetPlayer(int entityId)
        {
            if (OnlinePlayers.ContainsKey(entityId))
            {
                return(OnlinePlayers[entityId]);
            }

            return(null);
        }
 /// <summary>
 ///     Remove a player from the online players list and raise the according events
 /// </summary>
 /// <param name="player">The player to remove</param>
 public static void RemovePlayer(Player player)
 {
     if (player == null || !OnlinePlayers.ContainsKey(player.Name))
     {
         return;
     }
     OnlinePlayers.Remove(player.Name);
     RaisePlayerListChangedEvent();
     RaisePlayerListDeletionEvent(player);
 }
Exemple #8
0
 public void RemovePlayer(int entityId)
 {
     lock (OnlinePlayers)
     {
         if (OnlinePlayers.ContainsKey(entityId))
         {
             OnlinePlayers.Remove(entityId);
         }
     }
 }
        /// <inheritdoc />
        public bool TryGetOnlinePlayerById(string id, out IPlayer output)
        {
            IEnumerable <EcoPlayer> players = OnlinePlayers.Cast <EcoPlayer>();

            EcoPlayer player = players.FirstOrDefault(x => x.Id.Equals(id));

            output = player;

            return(player != null);
        }
Exemple #10
0
        private void GameTick(object source, ElapsedEventArgs e)
        {
            _sw.Start();

            DayTick();

            foreach (var blockEvent in BlockWithTicks.ToArray())
            {
                if (blockEvent.Value <= CurrentWorldTime)
                {
                    GetBlock(blockEvent.Key).OnTick(this);
                    int value;
                    BlockWithTicks.TryRemove(blockEvent.Key, out value);
                }
            }

            foreach (var player in OnlinePlayers.ToArray())
            {
                player.OnTick();
            }

            foreach (var entity in Entities.ToArray())
            {
                entity.OnTick();
            }

            if (_saveTick == 1500)
            {
                _saveTick = 0;
                ConsoleFunctions.WriteInfoLine("Saving chunks");
                var sw = new Stopwatch();
                sw.Start();
                SaveChunks();
                sw.Stop();
                ConsoleFunctions.WriteInfoLine("Saving chunks took: " + sw.ElapsedMilliseconds + "MS");

                ConsoleFunctions.WriteInfoLine("Clearing chunk cache...");
                Generator.ClearCache();       //Clear chunk cache
                GC.Collect();                 //Collect garbage
            }
            else
            {
                _saveTick++;
            }

            if (_saveTick == 750)
            {
                GC.Collect();
            }

            _sw.Stop();
            _lastCalc = _sw.ElapsedMilliseconds;
            _sw.Reset();
        }
Exemple #11
0
        /// <summary>
        /// Logs out.
        /// </summary>
        /// <param name="player">The player.</param>
        protected virtual void LogOut(Player player)
        {
            if (!OnlinePlayers.Remove(player))
            {
                return;
            }

            PlayerRepository.UpdatePlayerAsync(player);
            LoggedOut?.Invoke(this, player);
            Logger.Info($"[{player.Username}] logout succeed");
        }
Exemple #12
0
        public override void Update(GameTime gameTime)
        {
            if (GameMode == 1)
            {
                OnlinePlayers.Update();
            }
            if (!IsFrozen)
            {
                if ((KeyboardHelper.KeyHold(Keys.LeftControl) || KeyboardHelper.KeyHold(Keys.RightControl)) && KeyboardHelper.KeyPressed(Keys.K))
                {
                    ListLayer[0].LayerGrid = new Map3D(this, GraphicsDevice);
                }
                if ((KeyboardHelper.KeyHold(Keys.LeftControl) || KeyboardHelper.KeyHold(Keys.RightControl)) && KeyboardHelper.KeyPressed(Keys.L))
                {
                    ListLayer[0].LayerGrid = new CubeMap3D(this, GraphicsDevice);
                }
                if ((KeyboardHelper.KeyHold(Keys.LeftControl) || KeyboardHelper.KeyHold(Keys.RightControl)) && KeyboardHelper.KeyPressed(Keys.O))
                {
                    ListLayer[0].LayerGrid = new SphericalMap3D(this, GraphicsDevice);
                }
                if ((KeyboardHelper.KeyHold(Keys.LeftControl) || KeyboardHelper.KeyHold(Keys.RightControl)) && KeyboardHelper.KeyPressed(Keys.U))
                {
                    ListLayer[0].LayerGrid = ListLayer[0].OriginalLayerGrid;
                }

                foreach (MapLayer ActiveMapLayer in ListLayer)
                {
                    ActiveMapLayer.Update(gameTime);
                }

                if (ListNextAnimationScreen.Count > 0)
                {
                    PushScreen(ListNextAnimationScreen[0]);
                    ListNextAnimationScreen.Remove(ListNextAnimationScreen[0]);
                }
                else
                {
                    if (!IsInit)
                    {
                        Init();
                    }
                    else if (MovementAnimation.Count > 0)
                    {
                        MoveSquad();
                    }
                    else if (GameMode == 0 || (GameMode == 1 && !ListPlayer[ActivePlayerIndex].IsOnline))
                    {
                        ListActionMenuChoice.Last().Update(gameTime);
                    }

                    UpdateCursorVisiblePosition(gameTime);
                }
            }
        }
        /// <inheritdoc />
        public bool TryGetOnlinePlayerByName(string name, out IPlayer output)
        {
            IEnumerable <EcoPlayer> players = OnlinePlayers.Cast <EcoPlayer>();

            EcoPlayer player = players.FirstOrDefault(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
                               ?? players.FirstOrDefault(x => x.Name.ComparerContains(name));

            output = player;

            return(player != null);
        }
        private async Task UpdateGameServerAsync()
        {
            if (steamServerQueryService == null)
            {
                return;
            }
            IsBusy = true;
            try
            {
                Parsers.TryParseIPEndpoint(ServerAdress, out var endPoint);
                steamServerQueryService.EndPoint = endPoint;
                SteamServerInfo   serverInfo = null;
                List <PlayerInfo> playerInfo = null;
                try
                {
                    serverInfo = await steamServerQueryService.GetServerInfoAsync().ConfigureAwait(false);

                    playerInfo = (await steamServerQueryService.GetPlayersAsync().ConfigureAwait(false))?.Where(x => !string.IsNullOrEmpty(x.Name)).OrderBy(x => x.Name).ToList();
                }
                catch (Exception ex)
                {
                    ConnectError = true;
                    //Connected = false;
                    return;
                }
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    ConnectError = false;
                    Connected    = true;

                    PlayerCount = serverInfo.Players;
                    if (playerInfo != null)
                    {
                        if (OnlinePlayers == null)
                        {
                            OnlinePlayers = new ObservableRangeCollection <PlayerInfo>(playerInfo);
                        }
                        else
                        {
                            OnlinePlayers.ReplaceRange(playerInfo);
                        }
                        PlayerCount = OnlinePlayers.Count();
                    }
                    MaxPlayerCount = serverInfo.MaxPlayers;
                    ServerHeading  = $"{serverInfo.Name} ({PlayerCount}/{MaxPlayerCount})";
                }));
            }
            finally
            {
                IsBusy = false;
            }
        }
Exemple #15
0
        public void AddPlayer(Player player)
        {
            OnlinePlayers.Add(player);

            new PlayerListItem(player.Wrapper)
            {
                Action   = 0,
                Gamemode = player.Gamemode,
                Username = player.Username,
                UUID     = player.Uuid
            }.Broadcast(this);             //Send playerlist item to old players & player him self

            BroadcastExistingPlayers(player.Wrapper);
        }
Exemple #16
0
        public void AddPlayer(Player player)
        {
            OnlinePlayers.Add(player.EntityId, player);

            new PlayerListItem(player.Wrapper)
            {
                Action   = 0,
                Gamemode = player.Gamemode,
                Username = player.Username,
                Uuid     = player.Uuid
            }.Broadcast(this);             //Send playerlist item to old players & player him self

            IntroduceNewPlayer(player.Wrapper);
        }
Exemple #17
0
 public bool RecvPacket(PacketPlayerJoin p)
 {
     if (Identity == null)
     {
         Disconnect("Cannot do that without authenticating first!");
         return(false);
     }
     if (IsPlayerOnline(p.PlayerName))
     {
         Disconnect("Two of the same player on server!");
         return(false);
     }
     OnlinePlayers.Add(PlayerInstance.GetInstance(p.PlayerName));
     return(true);
 }
Exemple #18
0
 public bool RecvPacket(PacketPlayerLeave p)
 {
     if (Identity == null)
     {
         Disconnect("Cannot do that without authenticating first!");
         return(false);
     }
     for (int i = 0; i < OnlinePlayers.Count; i++)
     {
         if (OnlinePlayers[i].UserName == p.PlayerName)
         {
             OnlinePlayers.RemoveAt(i);
             return(true);
         }
     }
     Disconnect("Non-existant user disconnected?");
     return(false);
 }
        /// <summary>
        ///     Handle a player join event
        /// </summary>
        private static void HandlePlayerJoin(
            string text,
            OutputParseResult outputparseresult,
            IPlayerAction playeraction)
        {
            PlayerActionJoin join = (PlayerActionJoin)playeraction;

            Player player = new Player(join.PlayerName, join.Ip, join.PlayerName)
            {
                JoinTime = @join.Time
            };

            if (!OnlinePlayers.ContainsKey(player.Name))
            {
                OnlinePlayers.Add(player.Name, player);
            }
            RaisePlayerListChangedEvent();
        }
Exemple #20
0
        private void OnRecvLogin(IChannel channel, Message message)
        {
            CLogin request = message as CLogin;
            string scene   = "Level1";

            // read from database
            ConnectDB connect  = new ConnectDB();
            int       playerID = connect.LogIn(request.user, request.password);

            if (playerID == 0)
            {
                ClientTipInfo(channel, "Wrong UserName or Passwd!");
                return;
            }
            if (OnlinePlayers.ContainsKey(request.user))
            {
                ClientTipInfo(channel, "user has logged in!");
                return;
            }

            SPlayerEnter response = new SPlayerEnter()
            {
                user  = request.user,
                token = request.user,
                scene = scene
            };

            channel.Send(response);

            Player player = new Player(channel)
            {
                scene = scene
            };
            DEntity dentity = World.Instance.EntityData["Ellen"];

            player.FromDEntity(dentity);
            player.forClone = false;
            connect.GetPlayerAttri(playerID, player);
            Console.WriteLine("user: {0} login", player.user);

            // DOTO: Add xyz from db
        }
Exemple #21
0
        static Db()
        {
            var path = "C:\\Users\\admin\\Documents\\pfwdb.txt";

            //TODO save default path for dev purposes

            while (!File.Exists(path))
            {
                Console.WriteLine("Db connection string file not found, add path to file (will crash if no file): ");
                path = Console.ReadLine();
            }
            Console.WriteLine("Found db file in => " + path);
            string conStr = File.ReadAllText(path);

            Task.Run(delegate {
                while (true)
                {
                    Task.Delay(10000).Wait();
                    OnlinePlayers.DeleteManyAsync(x => x.LastOnline < DateTime.UtcNow - TimeSpan.FromSeconds(15));
                }
            });
        }
        /// <summary>
        ///     Add a player to the online players list and raise the according events
        /// </summary>
        /// <param name="player">The player to add</param>
        public static void AddPlayer(Player player)
        {
            if (player == null || string.IsNullOrEmpty(player.Name))
            {
                return;
            }

            try
            {
                if (OnlinePlayers.ContainsKey(player.Name))
                {
                    return;
                }

                OnlinePlayers.Add(player.Name, player);
                RaisePlayerListAdditionEvent(player);
                RaisePlayerListChangedEvent();
            }
            catch (Exception exception)
            {
                Logger.Log(LogLevel.Severe, "PlayerHandler", "Failed to add player: " + player.Name, exception.Message);
            }
        }
Exemple #23
0
        private void Initialize()
        {
            timerPlayerList      = new Timer((sender) => { UpdateOnlinePlayers(sender); }, this, 0, 30000);
            Players              = new PlayersCollection();
            Players.OnPlayerJoin = (player) => {
                if (player == null)
                {
                    return;
                }
                var existing = OnlinePlayers.FirstOrDefault(p => p.NickId.Equals(player.NickId));
                if (existing == null)
                {
                    lock (lockOnlinePlayers)
                    {
                        OnlinePlayers.Add(player);
                    }
                }
                else
                {
                    existing.Country = player.Country;
                }
            };
            Players.OnPlayerLeave = (player) => {
                if (player == null)
                {
                    lock (lockOnlinePlayers )
                    {
                        OnlinePlayers.RemoveAll(p => p.NickId.Equals(player.NickId));
                    }
                }
            };


            GameObjects      = new GameObjectsCollection();
            AirFields        = new AirFieldCollection();
            CoalitionIndexes = new List <CoalitionIndex>();
        }
Exemple #24
0
        private void UpdateOnlinePlayers(object sender)
        {
            bool playerListChanged = false;

            var server = sender as Server;

            if (sender == null ||
                !server.IsRconConnected ||
                Rcon == null)
            {
                return;
            }

            var newList = Rcon.GetPlayerList().With(list => list.Where(p => p != null));

            if (newList == null)
            {
                return;
            }

            if (newList.Count() == 0)
            {
                lock (server.lockOnlinePlayers)
                    OnlinePlayers.Clear();

                if (OnPlayerListChange != null)
                {
                    OnPlayerListChange(OnlinePlayers.ToList(), this);
                }

                return;
            }

            HashSet <Guid> onlineIds = new HashSet <Guid> (newList.Select(player => player.NickId));

            lock (server.lockOnlinePlayers)
            {
                playerListChanged = OnlinePlayers.Count(p => !onlineIds.Contains(p.NickId)) > 0;

                OnlinePlayers.RemoveAll(player => !onlineIds.Contains(player.NickId));

                foreach (var player in newList)
                {
                    var existing = OnlinePlayers.FirstOrDefault(p => p.NickId.Equals(player.NickId));
                    if (existing == null)
                    {
                        OnlinePlayers.Add(player);
                        playerListChanged = true;
                    }
                    else
                    {
                        if (!playerListChanged)
                        {
                            playerListChanged = existing.Ping != player.Ping ||
                                                existing.Status != player.Status ||
                                                existing.CoalitionIndex != player.CoalitionIndex;
                        }

                        existing.Ping           = player.Ping;
                        existing.Status         = player.Status;
                        existing.ClientId       = player.ClientId;
                        existing.CoalitionIndex = player.CoalitionIndex;
                    }
                }

                if (playerListChanged && OnPlayerListChange != null)
                {
                    OnPlayerListChange(OnlinePlayers.ToList(), this);
                }
            }
        }
Exemple #25
0
        private void OnRecvPlayerEnter(IChannel channel, Message message)
        {
            CPlayerEnter request = message as CPlayerEnter;
            Player       player  = (Player)channel.GetContent();
            Scene        scene   = World.Instance.GetScene(player.scene);

            // add the player to the scene
            player.Spawn();
            scene.AddEntity(player);

            // send player attributes
            SPlayerAttribute attrMessage = new SPlayerAttribute()
            {
                playerId     = player.entityId,
                name         = player.user,
                currentHP    = player.currentHP,
                level        = player.level,
                intelligence = player.intelligence,
                speed        = player.speed,
                attack       = player.attack,
                defense      = player.defense,
                GoldNum      = player.GoldNum,
                SilverNum    = player.SilverNum
            };

            channel.Send(attrMessage);

            // add online player
            OnlinePlayers.Add(player.user, player);
            // send oneline player to frontend
            Dictionary <int, string> SendDic = new Dictionary <int, string>();

            foreach (KeyValuePair <string, Player> tmp in OnlinePlayers)
            {
                SendDic.Add(tmp.Value.entityId, tmp.Key);
                Console.WriteLine("contains user:{0}", tmp.Key);
            }
            SFindFriends response = new SFindFriends()
            {
                friends = SendDic
            };

            player.Broadcast(response);


            // send treasure attributes
            ConnectDB connect = new ConnectDB();

            if (treasureAttributes.Count == 0)
            {
                treasureAttributes = new Dictionary <string, DTreasure>(connect.GetTreasureAttri());
            }
            STreasureAttribute treasureAttribute = new STreasureAttribute()
            {
                treasureAttri = new Dictionary <string, DTreasure>(treasureAttributes)
            };

            channel.Send(treasureAttribute);

            // send mall
            if (backMall.Count == 0)
            {
                backMall = new Dictionary <string, DTreasureMall>(connect.DBGetMall());
            }
            SMall mall = new SMall()
            {
                goods = new Dictionary <string, DTreasureMall>(backMall)
            };

            channel.Send(mall);

            // send package
            SPackage package = new SPackage()
            {
                goods = new Dictionary <string, DTreasurePackage>(connect.DBGetPackage(player.user))
            };

            channel.Send(package);

            // send friends
            SFriends friendList = new SFriends()
            {
                friends = new List <string>(connect.GetFriends(player.user))
            };

            channel.Send(friendList);

            // send friend requests
            SFindFriendRequests requestList = new SFindFriendRequests()
            {
                requests = new List <string>(connect.GetFriendRequest(player.user))
            };

            channel.Send(requestList);
        }
Exemple #26
0
 public IPlayer GetOnlinePlayer(string nameOrId)
 {
     return(OnlinePlayers.FirstOrDefault(c => c.Id.Equals(nameOrId, StringComparison.OrdinalIgnoreCase) ||
                                         c.Name.Equals(nameOrId, StringComparison.OrdinalIgnoreCase)));
 }
 /// <summary>
 ///     Check if a player is listed in the dictionarry of online players
 /// </summary>
 /// <param name="name">The name of the player to check</param>
 /// <returns>Returns true if the player is listed, false if the player isn't found</returns>
 public static Boolean IsPlayerListed(String name)
 {
     return(OnlinePlayers.ContainsKey(name));
 }
Exemple #28
0
        private void OnRecvBuy(IChannel channel, Message message)
        {
            Console.WriteLine("OnRecvBuy");
            CBuy      request  = message as CBuy;
            Player    player   = (Player)channel.GetContent();
            ConnectDB connect  = new ConnectDB();
            int       tmpJudge = 0;
            string    buyer_   = player.user;
            int       price_;
            string    seller_;
            Dictionary <string, int> newSilverGoods = new Dictionary <string, int>();
            Dictionary <string, int> oldSilverGoods = new Dictionary <string, int>();
            List <string>            goldGoods      = new List <string>();

            // resolve message
            foreach (DTreasureBuy goods in request.Goods)
            {
                if (goods.type == 0)
                {
                    goldGoods.Add(goods.name);
                }
                else if (goods.type == 1)
                {
                    newSilverGoods.Add(goods.name, goods.number);
                }
                else if (goods.type == 2)
                {
                    oldSilverGoods.Add(goods.name, goods.number);
                }
            }

            // transaction for gold treasures
            if (request.totalGold > 0)
            {
                // for each gold treasure is a transaction
                foreach (string goods in goldGoods)
                {
                    SBuyGoldResult goldMessage = new SBuyGoldResult();
                    goldMessage.goodsName = goods;
                    price_  = backMall[goods].price;
                    seller_ = backMall[goods].ownerName;
                    //Console.WriteLine("gold transcation: buyer: " + buyer_ + " seller: " + seller_ + " price: " + price_ + " goods: " + goods);
                    tmpJudge = connect.GoldTransaction(buyer_, seller_, price_, goods);
                    //Console.WriteLine("gold insert result: " + tmpJudge);
                    if (tmpJudge == 0)
                    {
                        goldMessage.success = false;
                    }
                    else
                    {
                        // send to seller
                        if (OnlinePlayers.ContainsKey(seller_))
                        {
                            Player toPlayer = OnlinePlayers[seller_];
                            toPlayer.GoldNum += price_;
                            SSendToSeller sellerMsg = new SSendToSeller()
                            {
                                goldCoin  = toPlayer.GoldNum,
                                goodsName = goods
                            };
                            toPlayer.connection.Send(sellerMsg);
                        }
                        // remove from backMalls
                        backMall.Remove(goods);
                        goldMessage.success = true;
                        // change player's goldCoin
                        player.GoldNum -= price_;
                    }
                    //Console.WriteLine("send goldMessage");
                    player.connection.Send(goldMessage);
                }
            }

            // deal with silver goods
            Console.WriteLine(request.totalSilver);
            if (request.totalSilver > 0)
            {
                // add treasure to package
                if (newSilverGoods.Count != 0)
                {
                    List <string> NewsilverTs = new List <string>();
                    foreach (KeyValuePair <string, int> goods in newSilverGoods)
                    {
                        //Console.WriteLine("new silver: buyer:" + buyer_ + " goods: " + goods.Key + " num: " + goods.Value);
                        NewsilverTs.Add(string.Format("('{0}','{1}','{2}')", buyer_, goods.Key, goods.Value));
                        //connect.AddTrade(goods.Key, "mall", buyer_, goods.Value, backMall[goods.Key].price);
                    }
                    tmpJudge = connect.BuyNewSilverTreasure(NewsilverTs);
                    //Console.WriteLine("new silver insert result: " + tmpJudge);
                }

                if (oldSilverGoods.Count != 0)
                {
                    foreach (KeyValuePair <string, int> goods in oldSilverGoods)
                    {
                        //Console.WriteLine("old silver: buyer:" + buyer_ + " goods: " + goods.Key + " num: " + goods.Value);
                        tmpJudge = connect.UpdateTreasureNum(buyer_, goods.Key, goods.Value);
                        connect.AddTrade(goods.Key, "mall", buyer_, goods.Value, backMall[goods.Key].price);
                        //Console.WriteLine("old silver insert result: " + tmpJudge);
                    }
                }

                // minus silver coins
                //Console.WriteLine("silverNum update result: " + tmpJudge);
                player.SilverNum -= request.totalSilver;
                //Console.WriteLine("player: " + buyer_ + " silverNum minus: " + request.totalSilver);
                tmpJudge = connect.UpdateSilverNum(buyer_, player.SilverNum);
            }
        }