/// <summary> /// Copy constructor. /// </summary> /// <param name="snakePart"></param> public SnakeBodyPart(SnakeBodyPart snakeBodyPart) { _gameBoardWidthPixels = snakeBodyPart.GameBoardWidthPixels; _gameBoardHeightPixels = snakeBodyPart.GameBoardHeightPixels; _xPosition = snakeBodyPart.XPosition; _yPosition = snakeBodyPart.YPosition; _width = snakeBodyPart.WidthPixels; _height = snakeBodyPart.HeightPixels; _directionOfTravel = snakeBodyPart.DirectionOfTravel; }
/// <summary> /// The UpdateSnakeStatus method is called to update the status of the snake. /// The snake's position is updated. /// Events are raised if the snake has hit a boundary, hit itself, or eaten the cherry. /// </summary> public void UpdateSnakeStatus(Cherry theCherry) { while (_updatingSnake) { Thread.Sleep(50); } _updatingSnake = true; TheSnakeHead.UpdatePosition(); // Update the position of the snake's head. TheSnakeEye.UpdatePosition(); // Update the position of the snake's eye. // Update the position of the snake's body. Direction previousDirection; Direction nextDirection = TheSnakeHead.DirectionOfTravel; foreach (SnakeBodyPart bodyPart in _snakeBody) { bodyPart.UpdatePosition(); previousDirection = bodyPart.DirectionOfTravel; bodyPart.DirectionOfTravel = nextDirection; nextDirection = previousDirection; } // Check if the snake has hit a boundary. if (TheSnakeHead.HitBoundary()) { // The snake has hit the boundary - raise an OnHitBoundary event. OnHitBoundary?.Invoke(); } // Check if the snake has hit itself. if (TheSnakeHead.HitSelf(_snakeBody)) { // The snake has hit itself - raise an OnHitSnake event. OnHitSnake?.Invoke(); } // Check if the snake can eat the cherry. if (TheSnakeHead.EatCherry(theCherry)) { // The snake has eaten the cherry - increase the length of the snake. SnakeBodyPart snakeBodyPart = new SnakeBodyPart(_gameBoardWidthPixels, _gameBoardHeightPixels, this); _snakeBody.Add(snakeBodyPart); // The snake has eaten the cherry - raise an OnEatCherry event. OnEatCherry?.Invoke(); } _updatingSnake = false; }