예제 #1
0
 /// <summary>
 /// Create an alive object
 /// </summary>
 /// <param name="team">the team of the game object</param>
 /// <param name="coords">the position of the game object</param>
 /// <param name="drawable">the image to draw</param>
 /// <param name="soundHandler">the song container</param>
 /// <param name="life">the life of the imageObject</param>
 /// <param name="speed">move speed in pixels</param>
 /// <param name="speedDecalage">move acceleration in pixels when the direction changes</param>
 public MovingObject(Team team, Vector2D coords, Drawable drawable, SoundHandler soundHandler, int life,
                     double speed, double speedDecalage) :
     base(team, coords, drawable, soundHandler, life)
 {
     Speed         = GameException.RequirePositive(speed);
     SpeedDecalage = GameException.RequirePositive(speedDecalage);
 }
예제 #2
0
        public void DisableNewGame(string clientVersion, string login, bool disable)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(login))
                {
                    throw new Exception("Доступ запрещён");
                }

#if !DEBUG
                //проверка версии клиента
                if (!string.IsNullOrEmpty(_UpdaterService.ClientVersion) && clientVersion != _UpdaterService.ClientVersion)
                {
                    throw new Exception($"Неверная версия клиента: login={login}.");
                }
#endif

                using (GamePortalEntities gamePortal = new GamePortalEntities())
                {
                    User gpUser = gamePortal.Users.FirstOrDefault(p => p.Login == login);
                    if (gpUser == null || !gpUser.Titles.Any(p => p.Name == "dynamic_title1*titleType_Создатель"))
                    {
                        throw new Exception("Доступ запрещён id" + gpUser?.Login);
                    }
                }

                IsDisableNewGame = disable;
            }
            catch (Exception exp)
            {
                GameException.NewGameException(null, "Service.DisableNewGame", exp, false);
            }
        }
예제 #3
0
 /// <summary>
 /// Create an alive object
 /// </summary>
 /// <param name="team">the team of the game object</param>
 /// <param name="coords">the position of the game object</param>
 /// <param name="drawable">the image to draw</param>
 /// <param name="soundHandler">the song container</param>
 /// <param name="life">the life of the imageObject</param>
 public AliveObject(Team team, Vector2D coords, Drawable drawable, SoundHandler soundHandler, int life) :
     base(team, coords, drawable)
 {
     Coords      -= new Vector2D(ImageDimentions.X / 2, 0);
     SoundHandler = GameException.RequireNonNull(soundHandler);
     Life         = (int)GameException.RequirePositive(life);
 }
예제 #4
0
 /// <summary>
 /// Stop a the playlist
 /// </summary>
 public void StopPlaylist()
 {
     foreach (MediaPlayer songs in GameException.RequireNonNull(Songs))
     {
         songs.Stop();
     }
 }
예제 #5
0
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception exp = e.ExceptionObject as Exception ?? new Exception(e.ExceptionObject.ToString());

            GameException.NewGameException(null, "Неизвестная ошибка.", exp, false);
            File.WriteAllText("Exception.txt", exp.ToString());

            this.Dispose();
        }
예제 #6
0
        /// <summary>
        /// Play the playlist
        /// </summary>
        public void PlayPlaylist()
        {
            StopPlaylist();

            if (GameException.RequireNonNull(Songs).Count != 0)
            {
                Songs[0].Play();
            }
        }
예제 #7
0
        public WCFGame NewGame(string clientVersion, WCFGameSettings gameSettings, string gamePassword)
        {
            try
            {
                if (IsDisableNewGame || gameSettings == null || !gameSettings.CheckInput())
                {
                    return(null);
                }

#if !DEBUG
                //проверка версии клиента
                if (!string.IsNullOrEmpty(_UpdaterService.ClientVersion) && clientVersion != _UpdaterService.ClientVersion)
                {
                    throw new Exception($"Неверная версия клиента: login={gameSettings.CreatorLogin}.");
                }
#endif

                WCFUser gpUser = _GamePortalService.GetProfileByLogin(gameSettings.CreatorLogin);

                //TODO проверка может ли пользователь поставить такие условия

                /*if (gpUser == null
                || gpUser.MindRate < gameSettings.RateSettings.MindRate
                || gpUser.HonorRate < gameSettings.RateSettings.HonorRate
                || gpUser.LikeRate < gameSettings.RateSettings.LikeRate
                || gpUser.DurationHours < gameSettings.RateSettings.DurationRate)
                ||  return Guid.Empty;*/

#if !DEBUG //запрет на много игр
                using (Agot2p6Entities dbContext = new Agot2p6Entities())
                {
                    if (dbContext.Game.Count(p => p.CloseTime == null && (p.CreatorLogin == gameSettings.CreatorLogin || p.GameUser.Any(p1 => !string.IsNullOrEmpty(p1.HomeType) && p1.Login == gameSettings.CreatorLogin))) > 0)
                    {
                        return(null);
                    }
                }
#endif

                WCFGame wcfGame = CreateGame(gameSettings, gamePassword);
                if (wcfGame == null)
                {
                    return(null);
                }

                //поднимаем хост и сообщаем о новой игре
                NewHost(wcfGame.Id);
                _NotifyService.AddGameNotifi(wcfGame);

                return(wcfGame);
            }
            catch (Exception exp)
            {
                GameException.NewGameException(null, "Не удалось создать игру.", exp, false);
                return(null);
            }
        }
예제 #8
0
 /// <summary>
 /// Create an animation from an image that can be divided in few images
 /// </summary>
 /// <param name="image">the graphics</param>
 /// <param name="lines">the numbers of lines in a single row</param>
 /// <param name="columns">the numbers of columns in a single line</param>
 public Animation(Bitmap image, int lines, int columns) :
     base(
         image,
         image.Width / (int)GameException.RequirePositive(columns),
         image.Height / (int)GameException.RequirePositive(lines)
         )
 {
     this.lines   = lines;
     this.columns = columns;
     Indexes      = new Vector2D(0, 0);
 }
예제 #9
0
        public void Update(GameException ex)
        {
            if (ex == null)
            {
                throw new System.ArgumentNullException(nameof(ex));
            }

            _tw.WriteLine();
            _tw.WriteLine(ex.Message);
            _tw.WriteLine();
        }
예제 #10
0
        private void OnWriteExceptionLog(GameException gameException)
        {
            LogWriter.LogInfo("Logger", $"Adding GameException {gameException.CurrentTick} to log...");
            // Only add the current game state to logs.
            gameExceptionLog.Add(gameException);
            if (gameExceptionLog.Count <= 0)
            {
                return;
            }

            WriteFileWithSerialisation(loggerConfig.GameExceptionLogFileName, logDirectory, gameExceptionLog.ToArray());
        }
예제 #11
0
 /// <summary>
 /// Draw the current image into the graphics
 /// </summary>
 /// <param name="graphics">the graphics</param>
 /// <param name="destination">top left position represented in pixels</param>
 public override void Draw(Graphics graphics, Vector2D destination)
 {
     GameException.RequireNonNull(destination);
     graphics.DrawImage(
         Image,
         new Rectangle(
             (int)destination.X,
             (int)destination.Y,
             Width,
             Height
             )
         );
 }
예제 #12
0
        /// <summary>
        ///     Handle GameComplete action.
        /// </summary>
        /// <returns></returns>
        public async Task SendGameException(GameException gameException)
        {
            Logger.LogDebug("GameException", gameException);
            var logger = runnerStateService.GetLogger();

            if (gameException.BotId == default)
            {
                gameException.BotId = runnerStateService.GetActiveConnections().FirstOrDefault(c => c.Value == Context.ConnectionId).Key;
            }

            if (logger != default)
            {
                await logger.Client.SendAsync("WriteExceptionLog", gameException);
            }
        }
예제 #13
0
        public void Should_Update_Hud_When_in_NextStep_throws_GameException()
        {
            // Given
            var ex = new GameException("expected message");

            _selector.Setup(s => s.GetByInput(_key))
            .Throws(ex);

            // When
            Target.NextStep();

            // Then
            _hud.Verify(h => h.Update(It.Is <GameException>(e => e.Message == ex.Message)));
            _hud.Verify(h => h.Update(_hero));
        }
예제 #14
0
 private void ChangeGameWhenLinkAccounts(string user, string linkUser)
 {
     try
     {
         using (Agot2p6Entities dbContext = new Agot2p6Entities())
         {
             dbContext.Game.Where(p => p.CreatorLogin == linkUser).ToList().ForEach(p => p.CreatorLogin = user);
             dbContext.GameUser.Where(p => p.Login == linkUser).ToList().ForEach(p => p.Login           = user);
             dbContext.SaveChanges();
         }
     }
     catch (Exception exp)
     {
         GameException.NewGameException(null, $"func=ChangeGameWhenLinkAccounts, user={user}, linkUser={linkUser}.", exp, false);
     }
 }
예제 #15
0
 public static string GetErrorMessage(GameException e)
 {
     if(e is BadServerPasswordException)
         return Catalog.GetString("Bad server administration password!");
     if(e is MaxPlayersOutOfRangeException)
         return Catalog.GetString("Maximum player count is out of range!");
     if(e is MinPlayersOutOfRangeException)
         return Catalog.GetString("Minimum player count is out of range!");
     if(e is MaxSpectatorsOutOfRangeException)
         return Catalog.GetString("Maximum spectator count is out of range!");
     if(e is InvalidIdException)
         return Catalog.GetString("Invalid identifier!");
     if(e is BadSessionStateException)
         return Catalog.GetString("Action is not valid for the current state of the session!");
     if(e is BadSessionPasswordException)
         return Catalog.GetString("Bad session password!");
     if(e is BadPlayerPasswordException)
         return Catalog.GetString("Bad player password!");
     if(e is TooManyPlayersException)
         return Catalog.GetString("Too many players!");
     if(e is TooManySpectatorsException)
         return Catalog.GetString("Too many spectators!");
     if(e is CannotReplacePlayerException)
         return Catalog.GetString("You can't replace this player!");
     if(e is MustBeCreatorException)
         return Catalog.GetString("You must be the creator of the session to perform this action!");
     if(e is BadGameStateException)
         return Catalog.GetString("Action is not valid for the current state of the game!");
     if(e is BadUsageException)
         return Catalog.GetString("This response is not valid!");
     if(e is BadPlayerException)
         return Catalog.GetString("Bad player!");
     if(e is BadCardException)
         return Catalog.GetString("Bad card!");
     if(e is BadCharacterTypeException)
         return Catalog.GetString("Bad character type!");
     if(e is BadTargetPlayerException)
         return Catalog.GetString("Bad target player!");
     if(e is BadTargetCardException)
         return Catalog.GetString("Bad target card!");
     if(e is CannotPlayBangException)
         return Catalog.GetString("You can play Bang only once in your turn!");
     if(e is CannotPlayBeerException)
         return Catalog.GetString("You can't play Beer when there are only two players left!");
     return Catalog.GetString("Unknown error!");
 }
예제 #16
0
        public void UpdateGamePoint(string clientVersion, string login, WCFGamePoint newPoint)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(login) || newPoint == null)
                {
                    throw new Exception("Некоректные данные");
                }

#if !DEBUG
                //проверка версии клиента
                if (!string.IsNullOrEmpty(_UpdaterService.ClientVersion) && clientVersion != _UpdaterService.ClientVersion)
                {
                    throw new Exception($"Неверная версия клиента: login={login}.");
                }
#endif

                using (GamePortalEntities gamePortal = new GamePortalEntities())
                {
                    User gpUser = gamePortal.Users.FirstOrDefault(p => p.Login == login);
                    if (gpUser == null || !gpUser.Titles.Any(p => p.Name == "dynamic_title1*titleType_Создатель"))
                    {
                        throw new Exception("Доступ запрещён id" + gpUser?.Login);
                    }
                }

                using (Agot2p6Entities dbContext = new Agot2p6Entities())
                {
                    GamePoint curPoint = dbContext.GamePoint.FirstOrDefault(p => p.Id == newPoint.Id);
                    if (curPoint == null)
                    {
                        throw new Exception("Неизвестная точка");
                    }

                    curPoint.X = newPoint.X;
                    curPoint.Y = newPoint.Y;

                    dbContext.SaveChanges();
                }
            }
            catch (Exception exp)
            {
                GameException.NewGameException(null, "Не удалось изменить точку:", exp, false);
            }
        }
예제 #17
0
        /// <summary>
        /// An gameObjet can is in collision with a projectile if
        /// the projectile meet a non transparent pixel of the DrawableObject
        /// </summary>
        /// <param name="projectile">projectile</param>
        /// <returns>Is the projectile in a non transparent pixel of the DrawableObject?</returns>
        public override bool CanCollision(ProjectileObject projectile)
        {
            GameException.RequireNonNull(projectile);

            if (Team == projectile.Team || !projectile.IsAlive())
            {
                return(false);
            }

            Rectangle intersect = Vector2D.Intersect(Coords, ImageDimentions, projectile.Coords, projectile.ImageDimentions);

            if (intersect.IsEmpty)
            {
                return(false);
            }

            return(IteratePixels(projectile, (x, y) => 0 < Drawable.Image.GetPixel(x, y).A));
        }
예제 #18
0
        /// <summary>
        /// Create shooter object
        /// </summary>
        /// <param name="src">initial position of the ennemy</param>
        /// <param name="dst">destination to reach before horizontal movement</param>
        /// <param name="drawable">image to draw</param>
        /// <param name="missileImage">projectile image to draw</param>
        /// <param name="speed">move speed in pixels</param>
        /// <param name="speedDecalage">move acceleration in pixels when the direction changes</param>
        /// <param name="shootPercentage">percentage to shoot by second between 0 and 100</param>
        /// <param name="life">life of the imageObject</param>
        public EnnemyObject(Vector2D src, Vector2D dst, Drawable drawable, Drawable missileImage, double speed,
                            double speedDecalage, int shootPercentage, int life) :
            base(Team.ENNEMY, GameException.RequireNonNull(src), drawable, ENNEMY_SOUNDS, speed, speedDecalage, life)
        {
            DestinationCoords = GameException.RequireNonNull(dst);
            MissileImage      = missileImage;
            ShootPercentage   = (int)GameException.RequirePositive(shootPercentage);

            // Every seconds, ...
            Timer = new Timer {
                Interval = 1000
            };

            // ..., the ennemy can try a shoot
            Timer.Elapsed += (object sender, ElapsedEventArgs e) => {
                TimeToShoot = true;
                Timer.Stop();
            };
        }
예제 #19
0
        public WCFService GetGame(string clientVersion, string login)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(login))
                {
                    return(null);
                }

#if !DEBUG
                //проверка версии клиента
                if (!string.IsNullOrEmpty(_UpdaterService.ClientVersion) && clientVersion != _UpdaterService.ClientVersion)
                {
                    return(null);
                }
#endif

                _GamePortalService.AddOnlineUser(login);

                WCFService result = new WCFService()
                {
                    IsDisableNewGame = IsDisableNewGame
                };
                using (Agot2p6Entities dbContext = new Agot2p6Entities())
                {
#if DEBUG
                    IEnumerable <Game> games = dbContext.Game.ToList().Where(p => GameHost.GameTypes.All(p1 => p.Id != p1.GameId));
#endif
#if !DEBUG
                    IQueryable <Game> games = dbContext.Game.Where(p => p.CreatorLogin != "System");
#endif
                    result.Games = games.ToList().Select(p => p.ToWCFGame()).ToList();
                }

                return(result);
            }
            catch (Exception exp)
            {
                GameException.NewGameException(null, "Не удалось подготовить список игр.", exp, false);
                return(null);
            }
        }
예제 #20
0
        /// <summary>
        /// Draw the current image into the graphics
        /// </summary>
        /// <param name="graphics">the graphics</param>
        /// <param name="destination">top left position represented in pixels</param>
        public override void Draw(Graphics graphics, Vector2D destination)
        {
            GameException.RequireNonNull(destination);
            graphics.DrawImage(
                Image,
                new Rectangle(
                    (int)destination.X, (int)destination.Y,
                    Width, Height
                    ),
                new Rectangle(
                    (int)Indexes.X * Width, (int)Indexes.Y * Height,
                    Width, Height
                    ),
                GraphicsUnit.Pixel
                );

            if (i++ % 10 == 0)
            {
                Next();
            }
        }
예제 #21
0
            public void Add(AutoConsole.Log error)
            {
                GameException ex = new GameException();

                ex.ScreenshotName = string.Format("EXCEPTION_{0}", Reported.Count);
                AutomationMaster.StaticSelfComponent.TakeScreenshotAsync(false, ex.ScreenshotName);
                ex.TimeStamp          = System.DateTime.UtcNow.ToLongDateString();
                ex.TestExecutionTime  = System.DateTime.UtcNow.Subtract(AutomationMaster.CurrentTestContext.StartTime).TotalSeconds.ToString();
                ex.CurrentRunningTest = AutomationMaster.CurrentTestContext.TestName;
                ex.Error        = AutomationReport.EncodeCharactersForJson(error.message);
                ex.ErrorDetails = AutomationReport.EncodeCharactersForJson(error.stackTrace);
                ex.Occurrences  = 1;
                for (int r = 0; r < Reported.Count; r++)
                {
                    if (Reported[r].Error == ex.Error && Reported[r].ErrorDetails == ex.ErrorDetails)
                    {
                        Reported[r].Occurrences++;
                        return;
                    }
                }
                _reported.Add(ex);
            }
예제 #22
0
            public void Add(AutoConsole.Log error)
            {
                GameException ex = new GameException();

                ex.ScreenshotName     = string.Format("EXCEPTION_{0}", Reported.Count);
                ex.TimeStamp          = System.DateTime.UtcNow.ToLongDateString();
                ex.TestExecutionTime  = System.DateTime.UtcNow.Subtract(AutomationMaster.CurrentTestContext.StartTime).TotalSeconds.ToString();
                ex.CurrentRunningTest = AutomationMaster.CurrentTestContext.TestName;
                ex.Error        = AutomationReport.EncodeCharactersForJson(error.message).Replace(AutomationMaster.DELIMITER.ToString(), "%7C");          //Encode AutomationMaster.DELIMITER character or errors will occur in data parsing in server.
                ex.ErrorDetails = AutomationReport.EncodeCharactersForJson(error.stackTrace).Replace(AutomationMaster.DELIMITER.ToString(), "%7C");       //Encode AutomationMaster.DELIMITER character or errors will occur in data parsing in server.
                ex.Occurrences  = 1;
                for (int r = 0; r < Reported.Count; r++)
                {
                    if (Reported[r].Error == ex.Error && Reported[r].ErrorDetails == ex.ErrorDetails)
                    {
                        Reported[r].Occurrences++;
                        return;
                    }
                }
                AutomationMaster.StaticSelfComponent.TakeScreenshotAsync(false, ex.ScreenshotName);                 //Only take a screenshot if it is not a duplicate. Spammed errors would lead to spammed screenshots.
                _reported.Add(ex);
            }
예제 #23
0
파일: Mouse.cs 프로젝트: Az3r/GameEngine
        /// <summary>
        /// All mouse events are not read immediately but stored in an events buffer, call <seealso cref="ReadInput"/> to read all mouse events
        /// </summary>
        public void ReadInput()
        {
            ClearReleasedState();
            while (EventsBuffer.Count > 0)
            {
                MouseEventArgs e = EventsBuffer.Dequeue();
                switch (e.Type)
                {
                case EventType.Down:
                    OnMouseDown(e.Buttons);
                    break;

                case EventType.Released:
                    OnMouseReleased(e.Buttons);
                    break;

                case EventType.Enter:
                    OnMouseEnter(e.Location);
                    break;

                case EventType.Leave:
                    OnMouseLeave(e.Location);
                    break;

                case EventType.Move:
                    OnMouseMove(e.Location);
                    break;

                case EventType.Wheel:
                    OnMouseWheel(e.Delta);
                    break;

                default:
                    GameException.Raise($"Event type is {e.Type}");
                    break;
                }
            }
        }
예제 #24
0
        /// <summary>
        /// Create a line of ennemies in a specific height
        /// </summary>
        /// <param name="factory">a factory that create a instance (that extends GameObject)</param>
        /// <param name="actualHeight">the height to insert objects</param>
        /// <param name="entityNb">the number of instance that you want to create</param>
        /// <param name="list">a optional list to stock the created instances</param>
        private void AddLine <v>(
            Func <Vector2D, Vector2D, v> factory,
            int actualHeight,
            int entityNb,
            List <v> list = null
            ) where v : GameObject
        {
            int size = (int)GameException.RequireNonZero(entityNb) * 2;
            int dx   = Game.Instance.GameSize.Width / size;

            for (int i = 1; i < size; i += 2)
            {
                v entity = factory(
                    new Vector2D(i * dx, 0),                                    // Begin coords
                    new Vector2D(i * dx, actualHeight)                          // Destination coords
                    );
                Game.Instance.AddNewGameObject(entity);
                if (list != null)
                {
                    list.Add(entity);
                }
            }
        }
예제 #25
0
        protected override void Update()
        {
            base.Update();
            var playerTransform = GameManager.player.transform;
            var dist            = Vector2.Distance(transform.position, playerTransform.position);

            if (dist < attackRange)
            {
                _currState = State.Attacking;
            }
            else if (dist < aggroRange)
            {
                _currState = State.Chasing;
            }
            else
            {
                _currState = State.Idle;
            }

            switch (_currState)
            {
            case State.Attacking:
                MainhandAttack(playerTransform.position);
                break;

            case State.Chasing:
                _controller.Direction = playerTransform.position - transform.position;
                break;

            case State.Idle:
                break;

            default:
                throw GameException.Error("Wtf? How did you get here???");
            }
        }
예제 #26
0
        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="route">路由</param>
        /// <param name="data">数据</param>
        public void postRequest(string route, JsonData data = null)
        {
            if (data == null)
            {
                Debug.Log("PostRequest: " + route + "\nData: null");
            }
            else
            {
                Debug.Log("PostRequest: " + route + "\nData: " + data.ToJson());
            }

            if (!isConnected())
            {
                GameException e = new GameException(GameException.Type.GameDisconnected);
                errorHandler.Invoke(e.code, e.message);
            }
            else
            {
                var sendData = setupSendData(route, data);
                var req      = pushRequestObject(route, sendData,
                                                 successHandler, errorHandler, showLoading, tipsText);
                doSendRequest(req);
            }
        }
예제 #27
0
 public void SetResponseType(string responseType, GameException exception = null)
 {
     responseLabel.Markup = "<span color='lightblue'>" + Catalog.GetString("Last response:") + " </span>";
     responseLabel.Markup += "<span color='orange'><b>" + responseType + " - </b></span>";
     if(exception == null)
         responseLabel.Markup += "<span color='lightgreen'>" + Catalog.GetString("Accepted!") + "</span>";
     else
         responseLabel.Markup += "<span color='lightsalmon'>" + MessageManager.GetErrorMessage(exception) + "</span>";
 }
예제 #28
0
 /// <summary>
 /// Play a sound
 /// </summary>
 public void PlaySFX(string url)
 {
     GameException.RequireNonNull(SFXDict)[url].Play();
 }
예제 #29
0
 /// <summary>
 /// Stop a SFX
 /// </summary>
 public void StopSFX(string url)
 {
     GameException.RequireNonNull(SFXDict)[url].Stop();
 }
예제 #30
0
 /// <summary>
 /// Return true if the gameObject is above of imageObject
 /// </summary>
 /// <param name="imageObject">the imageObject to compare</param>
 /// <returns>True if the gameObject is above of imageObject </returns>
 public bool IsAbove(DrawableObject imageObject)
 {
     return(Coords.Y < GameException.RequireNonNull(imageObject).Coords.Y);
 }
예제 #31
0
 /// <summary>
 /// Allow to a game object to be draw
 /// </summary>
 /// <param name="team">team of the game object</param>
 /// <param name="coords">coordinates of the gameObject</param>
 /// <param name="drawable">image to draw</param>
 public DrawableObject(Team team, Vector2D coords, View.Display.Images.Drawable drawable) : base(team, coords)
 {
     Drawable        = GameException.RequireNonNull(drawable);
     ImageDimentions = new Vector2D(drawable.Width, drawable.Height);
 }
예제 #32
0
 public void Update(GameException ex)
 {
 }