public void MoveSnake() { try { while (snakeParts.Count >= snakeLenght) { _canvas.Children.Remove(snakeParts[0].UiElement); snakeParts.RemoveAt(0); } foreach (SnakePart snakePart in snakeParts) { snakePart.IsHead = false; (snakePart.UiElement as Rectangle).Fill = snakeBodyColorBrush; } SnakePart snakeHead = snakeParts.Last(); int nextX = (int)snakeHead.Position.X; int nextY = (int)snakeHead.Position.Y; switch (SnakeDirection) { case SnakeDirections.Left: nextX -= _squareSize; break; case SnakeDirections.Right: nextX += _squareSize; break; case SnakeDirections.Up: nextY -= _squareSize; break; case SnakeDirections.Down: nextY += _squareSize; break; } SnakePart newSnakeHead = new SnakePart { IsHead = true, Position = new Point(nextX, nextY), }; snakeParts.Add(newSnakeHead); DrawSnake(); DoCheckCollision(); } catch (Exception ex) { throw; } }
private void DrawSnakeFood() { Point foodPosition = GetFoodPosition(); snakeFood = new SnakePart { Position = foodPosition, UiElement = new Ellipse { Width = _squareSize, Height = _squareSize, Fill = snakeFoodColorBrush } }; _canvas.Children.Add(snakeFood.UiElement); Canvas.SetTop(snakeFood.UiElement, snakeFood.Position.Y); Canvas.SetLeft(snakeFood.UiElement, snakeFood.Position.X); }
private void DoCheckCollision() { try { SnakePart snakeHead = snakeParts.First(x => x.IsHead); if (snakeHead.Position.X == snakeFood?.Position.X && snakeHead.Position.Y == snakeFood.Position.Y) { OnFoodEaten(); } if (snakeHead.Position.X >= _canvas.ActualWidth || snakeHead.Position.X < 0 || snakeHead.Position.Y >= _canvas.ActualHeight || snakeHead.Position.Y < 0 || snakeParts.Where(x => !x.IsHead && x.Position.X == snakeHead.Position.X && x.Position.Y == snakeHead.Position.Y).Count() > 0) { OnGameOver(); } } catch (Exception ex) { throw; } }
public void StartNewGame() { try { currentPoint = 0; snakeLenght = SnakeStartintLenght; SnakeDirection = SnakeDirections.Right; if (snakeParts != null) { foreach (SnakePart snakePart in snakeParts) { if (_canvas.Children.Contains(snakePart.UiElement)) { _canvas.Children.Remove(snakePart.UiElement); } } snakeParts.Clear(); } snakeParts.Add(new SnakePart { Position = new Point(_squareSize * 5, _squareSize * 5) }); DrawSnake(); if (snakeFood != null && _canvas.Children.Contains(snakeFood.UiElement)) { _canvas.Children.Remove(snakeFood.UiElement); snakeFood = null; } DrawSnakeFood(); OnNewGameStarted(); UpdateGameStatus(); } catch (Exception ex) { throw; } }