private void GenerateFood() { int posX = random.Next(Matrix.GetLength(0)); int posY = random.Next(Matrix.GetLength(1)); Matrix[posX, posY] = new FoodBlock(Matrix[posX, posY]); Console.WriteLine("New food created at " + Matrix[posX, posY]); }
/// <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; }
/// <summary> /// Checks if the <see cref="Snake"/> will eat a food block the next time it moves. /// </summary> /// <param name="snake">A <see cref="Snake"/> being checked if it will eat a food block.</param> /// <param name="food">A <see cref="FoodBlock"/> being checked if it will be eaten.</param> /// <param name="direction">A <see cref="Point"/> representing the direction the snake is moving.</param> /// <returns>true if the snake will hit a food block on it's next move; otherwise false.</returns> public static bool WillEatFood(Snake snake, FoodBlock food, Point direction) { // The position of the head of the snake. Point snakeHead = snake.SnakeBlocks.First.Value.Position; if (snakeHead.X + direction.X == food.Position.X && snakeHead.Y + direction.Y == food.Position.Y) { return(true); } else { return(false); } }
/// <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(); } }