Esempio n. 1
0
        public static void CalculateDot(MobData mob, List <MobStatusEffectModel> effects, double delta, Action <int> towerkilledCallback)
        {
            if (effects == null)
            {
                return;
            }

            if (effects.Any(se => se.Type == MobStatusEffect.Dot))
            {
                effects.Where(se => se.Type == MobStatusEffect.Dot).ToList().ForEach(se =>
                {
                    if (se.TimeSinceLastTick <= EffectTicksMilliseconds)
                    {
                        se.TimeSinceLastTick += delta;
                        return;
                    }
                    mob.Hp -= se.Value;
                    if (mob.Hp <= 0)
                    {
                        if (towerkilledCallback != null)
                        {
                            towerkilledCallback(se.SenderTowerId);
                        }
                        else
                        {
                            TStuffLog.Debug("Tower Killed Callback is not Set");
                        }
                    }
                    se.TimeSinceLastTick = 0;
                });
            }
        }
        private void ProcessGame(double delta, double total)
        {
            switch (_session.State)
            {
            case GameState.LoadState:
                DoLoadStep(delta);
                break;

            case GameState.PlayState:
                try
                {
                    PreUpdate(delta);
                    Update(delta);
                    PostUpdate(delta);
                }
                catch (Exception ex)
                {
                    TStuffLog.Error(ex.ToString());
                }
                break;

            case GameState.FinishState:
                break;
            }
        }
        private void StartupGame(GameSession session)
        {
            session.State = GameState.LoadState;
            session.Players.ForEach(p => p.State = PlayerState.Loading);
            try
            {
                var mapLoader = new MapFromImageParser(session.SelectedMap);
                session.MapData = mapLoader.ParseImage();

                session.MapHandler = new ServerMap(session);

                if (session.Players.Count == 1)
                {
                    AddRace(session, 1, 0, 0);
                    //AddRace(session, 0, 1, 0);
                    //AddRace(session, 2, 2, 1);
                    //AddRace(session, 3, 3, 1);
                }

                session.GameLoop = new GameLoop(_gr, session);
            }
            catch (Exception ex)
            {
                TStuffLog.Error(ex.ToString());
            }
            session.Players.ForEach(p => p.User.Send(RequestNames.GetMapData, session.MapData));
        }
 private void MaintainGameSession(double delta)
 {
     _lastAliveMsg += delta;
     if (_lastAliveMsg >= GConfig.D.GameSessionLoopAliveMessageAfterSeconds * GConfig.D.GameSimulationTime)
     {
         TStuffLog.Info("Game loop of Session: " + _session.Id + " is alive!");
         _lastAliveMsg = 0;
     }
 }
Esempio n. 5
0
        public void RemoveUser(Connection connection)
        {
            var user = GetUserByConnection(connection);

            if (user != null)
            {
                TStuffLog.Info("Remove user: " + user.Name);
                _users.Remove(user);
            }
        }
Esempio n. 6
0
        private void GenerateHeader()
        {
            var mapHeader = new Dictionary <TileType, int>();

            for (int x = 0; x < _map.ColorDefinitionCols; x++)
            {
                for (int y = 0; y < _map.ColorDefinitionRows; y++)
                {
                    var color = _mapImage.GetPixel(x, y);
                    TStuffLog.Debug(color.ToString() + " x: " + x + " y: " + y);
                }
            }
        }
        private void CreateGameWithSettings(User user, GameSettings incomingObject)
        {
            //If a user has allready a GameSession
            if (_gr.GameSessions.GetSessionByUserId(user) != null)
            {
                user.Send(RequestNames.Message, new ClientMessage {
                    Message = "There exists a game which you have created!", MessageType = MessageType.Error, Title = "Create Game Error"
                });
                return;
            }
            ;

            _gr.GameSessions.CreateGameSession(user, incomingObject);
            TStuffLog.Info("Game Startet!");
            //Join Connection Player;
        }
        private void ProcessMapRequests(Connection connection, MapRequests incomingObject)
        {
            var user = _gr.User.GetUserByConnection(connection);

            TStuffLog.Debug($"Incomming Request with: {incomingObject.Request.ToString()}");
            //DemoMaps
            switch (incomingObject.Request)
            {
            case MapRequestTypes.GetAllMaps:
                SendMapListToClient(user);
                break;

            case MapRequestTypes.GetOpenGames:
                SendOpenGames(user);
                break;
            }
        }
        public void Update(double delta)
        {
            var targetToRemove = Targets.Where(a => a.IsDead || !IsInDistance(X, Y, a.X, a.Y)).ToList();

            targetToRemove.ForEach(w =>
            {
                Targets.Remove(w);
                hasChanged = true;
            });

            if (_fireCooldown > 0)
            {
                _fireCooldown -= delta;
            }

            if (Targets.Count < TowerData.MaxTargets)
            {
                try
                {
                    SearchTarget();
                }
                catch (Exception ex)
                {
                    TStuffLog.Error(ex.ToString());
                }
            }

            Targets.ForEach(t =>
            {
                if (_fireCooldown <= 0)
                {
                    _fireCooldown = TowerData.FireSpeed;
                    AttackTarget(t);
                }
                IsFire     = true;
                hasChanged = true;
            });

            if (Targets.Count == 0)
            {
                IsFire     = false;
                hasChanged = true;
            }
        }
        private static void SetupGlobalNetworkHandler(GlobalRegister gamecontext)
        {
            #region Global Handler

            NetworkComms.AppendGlobalConnectionEstablishHandler(connection => { TStuffLog.Debug("Icomming connection"); });
            NetworkComms.AppendGlobalConnectionCloseHandler(connection =>
            {
                gamecontext.GameSessions.LeaveGame(connection);
                gamecontext.User.RemoveUser(connection);
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <EchoObject>("echo", (header, connection, incomingObject) =>
            {
                TStuffLog.Debug("Echo Object");
                TStuffLog.Debug($"Object info {incomingObject.Id} - {incomingObject.Message}");
                connection.SendObject("echo", incomingObject);
            });

            #endregion
        }
 private bool IsTowerCollision(double delta)
 {
     if (_session.MapHandler.IsTowerOnPosition(CurrentGoal.X, CurrentGoal.Y))
     {
         if (!UpdatePath())
         {
             IsBlocked      = true;
             _destroyTimer += delta;
             TStuffLog.Debug("I Wait");
             if (_destroyTimer >= _waitBeforeDestroy)
             {
                 _session.MapHandler.DestroyTower(this, CurrentGoal.X, CurrentGoal.Y);
                 _destroyTimer = 0;
             }
             return(true);
         }
         _destroyTimer = 0;
         IsBlocked     = false;
     }
     return(false);
 }
        private List <Tuple <MapTile, MapTile, MapTile> > BuildSpawnListByTeam4()
        {
            var spawnList = new List <Tuple <MapTile, MapTile, MapTile> >();

            try
            {
                var spawnTile = _session.MapData.Data.Single(a => a.Type == TileType.Path1Team4Start);
                var wayTile   = _session.MapData.Data.SingleOrDefault(a => a.Type == TileType.Path1Team4Way);
                var endTile   = _session.MapData.Data.Single(a => a.Type == TileType.Path1Team4end);
                spawnList.Add(new Tuple <MapTile, MapTile, MapTile>(spawnTile, wayTile, endTile));
            }
            catch { TStuffLog.Debug("Cant load Path"); }
            try
            {
                var spawnTileoMapTile = _session.MapData.Data.Single(a => a.Type == TileType.Path2Team4Start);
                var wayTileo          = _session.MapData.Data.SingleOrDefault(a => a.Type == TileType.Path2Team4Way);
                var endTileo          = _session.MapData.Data.Single(a => a.Type == TileType.Path2Team4end);
                spawnList.Add(new Tuple <MapTile, MapTile, MapTile>(spawnTileoMapTile, wayTileo, endTileo));
            }
            catch { TStuffLog.Debug("Cant load Path"); }
            try
            {
                var spawnTileoMapTile = _session.MapData.Data.Single(a => a.Type == TileType.Path3Team4Start);
                var wayTileo          = _session.MapData.Data.SingleOrDefault(a => a.Type == TileType.Path3Team4Way);
                var endTileo          = _session.MapData.Data.Single(a => a.Type == TileType.Path3Team4end);
                spawnList.Add(new Tuple <MapTile, MapTile, MapTile>(spawnTileoMapTile, wayTileo, endTileo));
            }
            catch { TStuffLog.Debug("Cant load Path"); }
            try
            {
                var spawnTileoMapTile = _session.MapData.Data.Single(a => a.Type == TileType.Path4Team4Start);
                var wayTileo          = _session.MapData.Data.SingleOrDefault(a => a.Type == TileType.Path4Team4Way);
                var endTileo          = _session.MapData.Data.Single(a => a.Type == TileType.Path4Team4end);
                spawnList.Add(new Tuple <MapTile, MapTile, MapTile>(spawnTileoMapTile, wayTileo, endTileo));
            }
            catch { TStuffLog.Debug("Cant load Path"); }


            return(spawnList);
        }
        private void SendUpdate()
        {
            if (_fastUpdateObjectQueue.Count == 0)
            {
                return;
            }
            var fu = _fastUpdateObjectQueue.Pop();

            if (fu == null)
            {
                return;
            }

            _session.Players.ForEach(p =>
            {
                try
                {
                    p.User.Send(RequestNames.FastUpdate, fu);
                }
                catch (Exception ex) { TStuffLog.Error(ex.StackTrace); }
            });
        }
Esempio n. 14
0
        public void Process(Connection con, Login login)
        {
            TStuffLog.Debug("Get Login");

            if (_userHandler.Login(con, login))
            {
                TStuffLog.Info("Login for: " + login.Name + " Successfull");
                //Update Game data
                var user = _userHandler.GetUserByConnection(con);
                user.Send(RequestNames.GetObjectDb, new RaceModels
                {
                    TowerRaces = _gr.TowerRaces.ToArray(),
                    MobRaces   = _gr.MobRaces.ToArray(),
                    Towers     = _gr.Towers.ToArray(),
                    Mobs       = _gr.Mobs.ToArray()
                });
            }
            else
            {
                TStuffLog.Warning("Login Error!");
            }
        }
Esempio n. 15
0
        public void LeaveGame(Connection connection)
        {
            var session = GetSessionByConnection(connection);
            var user    = _gr.User.GetUserByConnection(connection);

            if (session != null)
            {
                var player = (session?.Players).SingleOrDefault(a => a.User.Id == user.Id);
                if (player == null)
                {
                    return;
                }
                if (player.Owner)
                {
                    CancelGame(session);
                }
                else
                {
                    session.Players.Remove(player);
                    foreach (var team in session.Teams)
                    {
                        team.Value.Remove(player);
                    }
                    try
                    {
                        user.Send(RequestNames.GameNotification,
                                  new GameNotifications {
                            Notification = GameNotificationType.GameCanceled
                        });
                    }
                    catch (Exception ex) { TStuffLog.Error("Notification GameCancle " + ex); }
                    session.Players.ForEach(p =>
                    {
                        p.User.Send(RequestNames.GameJoinInfo, GetGameJoinInfo(session));
                    });
                }
            }
        }
        private void ProcessGameNotifications(GameNotifications incomingObject, Connection connection)
        {
            var user    = _gr.User.GetUserByConnection(connection);
            var session = _gr.GameSessions.GetSessionByUserId(user);
            var player  = session.Players.Single(p => p.User.Id == user.Id);

            switch (incomingObject.Notification)
            {
            case GameNotificationType.GameCanceled:
            case GameNotificationType.LeaveGame:
                _gr.GameSessions.LeaveGame(connection);
                return;

            case GameNotificationType.Ready:
                session.Players.Single(p => p.User.Id == user.Id).State = incomingObject.IntValue == 1 ? PlayerState.Ready : PlayerState.Joined;
                break;

            case GameNotificationType.ChangeTeam:

                session.Teams.Single(p => p.Value.Any(x => x.User.Id == user.Id)).Value.Remove(player);
                session.Teams[incomingObject.IntValue].Add(player);
                player.TeamId = incomingObject.IntValue;
                break;

            case GameNotificationType.StartGame:
                TStuffLog.Info("Start Game");
                //BotAdd
                StartupGame(session);
                break;
            }

            var joinInfo = _gr.GameSessions.GetGameJoinInfo(session);

            session.Players.ForEach(p =>
            {
                p.User.Send(RequestNames.GameJoinInfo, joinInfo);
            });
        }
Esempio n. 17
0
        private void CancelGame(GameSession session)
        {
            session.Players.ForEach(p =>
            {
                try
                {
                    p.User.CurrentSession = null;
                    p.User.Send(RequestNames.GameNotification,
                                new GameNotifications {
                        Notification = GameNotificationType.GameCanceled
                    });
                }
                catch (Exception ex)
                {
                    TStuffLog.Error(ex.ToString());
                }
            });

            session.Players.Clear();
            session.GameMobs.Clear();
            session.GameTower.Clear();
            session.Dispose();
            Sessions.Remove(session);
        }
        public GameLoop(GlobalRegister gr, GameSession session)
        {
            TStuffLog.Info("Start Gameloop");
            _gr      = gr;
            _session = session;
            InitializeGameLoopData();



            _startTime = new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds;
            _lastTime  = _startTime;
            _gameTimer = new Timer(state =>
            {
                var delta = new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds - _lastTime;
                var total = new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds - _startTime;
                MaintainGameSession(delta);
                ProcessGame(delta, total);
                _lastTime = new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds;
            }, null, 0, GConfig.D.LogicUpdateEachMillisecond);
            _startSendTime   = new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds;
            _lastSendTime    = _startTime;
            _sendUpdateTimer = new Timer(state =>
            {
                var delta = new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds - _lastSendTime;
                var total = new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds - _startSendTime;
                try
                {
                    SendDataState(delta);
                }
                catch (Exception ex)
                {
                    TStuffLog.Error(ex.ToString());
                }
                _lastSendTime = new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds;
            }, null, 0, GConfig.D.SendLoopMilliseconds);
        }
        private List <Tuple <MapTile, MapTile, MapTile> > BuildSpawnListByTeam2()
        {
            var spawnList = new List <Tuple <MapTile, MapTile, MapTile> >();
            var spawnTile = _session.MapData.Data.Single(a => a.Type == TileType.Path1Team2Start);
            var wayTile   = _session.MapData.Data.SingleOrDefault(a => a.Type == TileType.Path1Team2Way);
            var endTile   = _session.MapData.Data.Single(a => a.Type == TileType.Path1Team2end);

            spawnList.Add(new Tuple <MapTile, MapTile, MapTile>(spawnTile, wayTile, endTile));
            try
            {
                var spawnTileoMapTile = _session.MapData.Data.Single(a => a.Type == TileType.Path2Team2Start);
                var wayTileo          = _session.MapData.Data.SingleOrDefault(a => a.Type == TileType.Path2Team2Way);
                var endTileo          = _session.MapData.Data.Single(a => a.Type == TileType.Path2Team2end);
                spawnList.Add(new Tuple <MapTile, MapTile, MapTile>(spawnTileoMapTile, wayTileo, endTileo));
            }
            catch (Exception ex) { TStuffLog.Debug("Cant load Team 2 Path 2: " + ex.Message); }
            try
            {
                var spawnTileoMapTile = _session.MapData.Data.Single(a => a.Type == TileType.Path3Team2Start);
                var wayTileo          = _session.MapData.Data.SingleOrDefault(a => a.Type == TileType.Path3Team2Way);
                var endTileo          = _session.MapData.Data.Single(a => a.Type == TileType.Path3Team2end);
                spawnList.Add(new Tuple <MapTile, MapTile, MapTile>(spawnTileoMapTile, wayTileo, endTileo));
            }
            catch (Exception ex) { TStuffLog.Debug("Cant load Team 2 Path 3: " + ex.Message); }
            try
            {
                var spawnTileoMapTile = _session.MapData.Data.Single(a => a.Type == TileType.Path4Team2Start);
                var wayTileo          = _session.MapData.Data.SingleOrDefault(a => a.Type == TileType.Path4Team2Way);
                var endTileo          = _session.MapData.Data.Single(a => a.Type == TileType.Path4Team2end);
                spawnList.Add(new Tuple <MapTile, MapTile, MapTile>(spawnTileoMapTile, wayTileo, endTileo));
            }
            catch (Exception ex) { TStuffLog.Debug("Cant load Team 2 Path 4: " + ex.Message); }


            return(spawnList);
        }
Esempio n. 20
0
 public void Dispose()
 {
     TStuffLog.Info("Game Session is disposed");
     GameLoop?.StopLoop();
 }
        static void Main(string[] args)
        {
            TStuffLog.LogLevel     = LogLevel.Info;
            TStuffLog.LogFileLevel = LogLevel.Info;
            TStuffLog.LogActions.Add((message, serializedObject, level, member, filepat, line) =>
            {
                if (TStuffLog.LogLevel > level)
                {
                    return;
                }
                switch (level)
                {
                case LogLevel.Trace:
                    Console.ForegroundColor = ConsoleColor.Green;
                    break;

                case LogLevel.Debug:
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    break;

                case LogLevel.Info:

                    break;

                case LogLevel.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;

                case LogLevel.Error:
                case LogLevel.Fatal:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(level), level, null);
                }
                Console.WriteLine("[{5},{0}/{1}:{2}, Level:{3}] Message: {4}", filepat.Split('\\').Last(), member, line, level.ToString(), message, DateTime.Now.ToString("T"));
                Console.ResetColor();
            });

            NetworkComms.DisableLogging();

            if (File.Exists("config.json"))
            {
                GConfig.D = JsonConvert.DeserializeObject <GameServerConfiguration>(File.ReadAllText("config.json"));
            }
            else
            {
                GConfig.D = new GameServerConfiguration();
                File.WriteAllText("config.json", JsonConvert.SerializeObject(GConfig.D, Formatting.Indented));
            }
            TStuffLog.Info("Server Started");
            TStuffLog.LogLevel     = GConfig.D.ServerLogLevel;
            TStuffLog.LogFileLevel = GConfig.D.LogFileLevel;

            DataSerializer ds = DPSManager.GetDataSerializer <ProtobufSerializer>();

            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(ds, new List <DataProcessor>(), new Dictionary <string, string>());
            var gamecontext = SetupGameRegister();

            SetupGlobalNetworkHandler(gamecontext);

            GConfig.D.GameSimulationTime = 400;
            var cont = new LoginService(gamecontext);
            var map  = new CreateGameService(gamecontext);


            Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, GConfig.D.ServerPort));
            //Connectc fake user
            gamecontext.User.AddSystemUser(GConfig.D.MainBotName + " 0", 0);
            gamecontext.User.AddSystemUser(GConfig.D.MainBotName + " 1", 1);
            gamecontext.User.AddSystemUser(GConfig.D.MainBotName + " 2", 2);
            gamecontext.User.AddSystemUser(GConfig.D.MainBotName + " 3", 3);
            gamecontext.User.AddSystemUser(GConfig.D.MainBotName + " 4", 4);


            //File.WriteAllText("mobs.json",JsonConvert.SerializeObject(gamecontext.Mobs));
            //File.WriteAllText("tower.json", JsonConvert.SerializeObject(gamecontext.Towers));
            //File.WriteAllText("race_mob.json", JsonConvert.SerializeObject(gamecontext.MobRaces));
            //File.WriteAllText("race_tower.json", JsonConvert.SerializeObject(gamecontext.TowerRaces));

            Console.ReadLine();
        }