// SnakeFood constructor. public SnakeFood(List <SnakePart> snakeParts, List <SnakeFood> snakeFoods) { int foodSize = snakeParts[0].ElementSize; bool isAvailable = false; List <Point> occupiedPoints = new List <Point>(); foreach (SnakePart snakePart in snakeParts) { occupiedPoints.Add(snakePart.CurrentPosition); } foreach (SnakeFood snakeFood in snakeFoods) { occupiedPoints.Add(snakeFood.CurrentPosition); } // Draw coordinates of a snake food point. this.ElementSize = foodSize; Random random = new Random(); int randomX, randomY; // Check if the snake food point is the same as one of the snake parts points. // or one of other snake foods points. If yes, draw again do { randomX = random.Next(0, 24) * 20; randomY = random.Next(0, 24) * 20; this.CurrentPosition = new Point(randomX, randomY); isAvailable = SnakeFood.CheckPointAvailability(occupiedPoints, this.CurrentPosition); }while (!isAvailable); }
// Check if the snake ate food method. public bool Check() { // Assign the first element of the snake parts list // which is always the snake's head. SnakePart snakeHead = _snakeParts[0]; foreach (SnakeFood snakeFood in _snakeFoods) { if (snakeHead.CurrentPosition == snakeFood.CurrentPosition) { _eatenSnakeFood = snakeFood; return(true); } } return(false); }
// Behavior if snake ate food. public void Eaten(Canvas gameBoard, int maxSnakeSpeed, ref int score, ref DispatcherTimer timer, string foodImagePath) { // Increment score. score++; // Increase a snake speed. int timeInterval = Math.Max((10000000 - score * 500000), maxSnakeSpeed); timer.Interval = new TimeSpan(timeInterval); // Delete the eaten food element. gameBoard.Children.Remove(_eatenSnakeFood.ElementRepresentation); _snakeFoods.Remove(_eatenSnakeFood); // Create a new food element. SnakeFood newSnakeFood = new SnakeFood(_snakeParts, _snakeFoods); _snakeFoods.Add(newSnakeFood); newSnakeFood.Paint(gameBoard, foodImagePath); }