Пример #1
0
 /// <summary>
 /// Event which is used to determine the direction to move the <see cref="Snake"/>.
 /// </summary>
 /// <param name="sender">An <see cref="object"/> representing the source of the event.</param>
 /// <param name="e">An <see cref="EventArgs"/> containing the event data.</param>
 private void SnakeGame_KeyDown(object sender, KeyEventArgs e)
 {
     if (this.canRestart && e.KeyData == Keys.Space)
     {
         this.canRestart = false;
         this.NewGame();
     }
     else
     {
         this.direction = SnakeUtility.ChangeDirection(this.direction, this.previousDirection, e.KeyData);
     }
 }
Пример #2
0
 /// <summary>
 /// Creates/Recreates the game and then starts it.
 /// </summary>
 private void NewGame()
 {
     this.Controls.Clear();
     this.gridSize       = new Size(this.ClientSize.Width / BaseBlock.StandardBlockSize.Width, this.ClientSize.Height / BaseBlock.StandardBlockSize.Height);
     this.snake          = new Snake(SnakeGame.DefaultSnakeLength);
     this.emptyPositions = SnakeUtility.GetEmptyBlockPositions(this.snake, this.gridSize);
     this.food           = new FoodBlock(this.emptyPositions);
     this.direction      = new Point(0, 1);
     this.state          = GameState.Playing;
     this.Invalidate();
     this.gameTimer.Enabled = true;
 }
Пример #3
0
        /// <summary>
        /// Performs the main loop of game which is ran on every tick of the game timer.
        /// </summary>
        private void GameLoop()
        {
            if (this.direction.X == 0 && this.direction.Y == 0)
            {
                return;
            }

            if (SnakeUtility.WillEatFood(this.snake, this.food, this.direction))
            {
                this.snake.Grow();
                this.emptyPositions = SnakeUtility.GetEmptyBlockPositions(this.snake, this.gridSize);
                this.food           = new FoodBlock(this.emptyPositions);
            }

            this.snake.Move(this.direction);
            this.previousDirection = this.direction;

            if (SnakeUtility.HasCollidedWithSelf(this.snake) || SnakeUtility.HasHitBounds(this.snake, this.gridSize.Width, this.gridSize.Height) || this.emptyPositions.Count == 0)
            {
                this.GameOver();
            }
        }