static void Initialise() { Points = new Queue <Position>(); SnakeSpeed = INITIAL_MILLIS_PER_MOVEMENT; LastMovement = DateTime.Now; Direction = SnakeDirection.Right; LastKeyPressed = ConsoleKey.RightArrow; // Set window size Console.SetWindowSize(CONSOLE_WIDTH + (CONSOLE_PADDING * 2), CONSOLE_HEIGHT + (CONSOLE_PADDING * 2)); Console.SetBufferSize(CONSOLE_WIDTH + (CONSOLE_PADDING * 2), CONSOLE_HEIGHT + (CONSOLE_PADDING * 2)); // Initialise the scoreboard Score = 0; isDead = false; // Create the snake int MidScreenWidth = CONSOLE_WIDTH / 2; int MidScreenHeight = CONSOLE_HEIGHT / 2; for (int i = 0; i < INITIAL_SNAKE_LENGTH; i++) { Points.Enqueue(new Position(MidScreenWidth + i, MidScreenHeight)); } // Create the food SpawnFood(); }
private void StartNewGame() { // Clear Game OverContent label. textWrapGameOver.Text = ""; // Remove potential dead snake parts and leftover food... foreach (SnakePart snakeBodyPart in snakeParts) { if (snakeBodyPart.UiElement != null) { GameArea.Children.Remove(snakeBodyPart.UiElement); } } snakeParts.Clear(); if (snakeFood != null) { GameArea.Children.Remove(snakeFood); } currentScore = 0; snakeLength = SnakeStartLength; snakeDirection = SnakeDirection.Right; snakeParts.Add(new SnakePart() { Position = new Point(SnakePartSize * 5, SnakePartSize * 5) }); gameTickTimer.Interval = TimeSpan.FromMilliseconds(SnakeStartSpeed); DrawSnakeBody(); DrawSnakeFood(); // Start: gameTickTimer.IsEnabled = true; }
public SnakeSegment(Sprite sprite, Vector2 position, float rotation, SnakeDirection direction) { Sprite = sprite; Position = position; Rotation = rotation; Direction = direction; }
private void Form1_KeyPress(object sender, KeyPressEventArgs e) { switch (e.KeyChar) { case 'w': if (snakeDirection != SnakeDirection.Down) { snakeDirection = SnakeDirection.Up; } break; case 'd': if (snakeDirection != SnakeDirection.Left) { snakeDirection = SnakeDirection.Right; } break; case 's': if (snakeDirection != SnakeDirection.Up) { snakeDirection = SnakeDirection.Down; } break; case 'a': if (snakeDirection != SnakeDirection.Right) { snakeDirection = SnakeDirection.Left; } break; } }
public SnakeDirection GetNextDirection(SnakeDirection currentDirection) { if (currentDirection == SnakeDirection.Up && _myHeadPosition.Y < _wallDistanceThreshold) { return(SnakeDirection.Left); } if (currentDirection == SnakeDirection.Right && _myHeadPosition.X > _width - _wallDistanceThreshold) { return(SnakeDirection.Up); } if (currentDirection == SnakeDirection.Down && _myHeadPosition.Y > _width - _wallDistanceThreshold) { return(SnakeDirection.Right); } if (currentDirection == SnakeDirection.Left && _myHeadPosition.X < _wallDistanceThreshold) { return(SnakeDirection.Down); } return(currentDirection); }
private void StartNewGame() { snakeLength = SnakeStartLength; snakeDirection = SnakeDirection.Right; snakeParts.Add(new SnakePart() { Position = new Point(SnakeSquareSize * 5, SnakeSquareSize * 5) }); gameTickTimer.Interval = TimeSpan.FromMilliseconds(SnakeStartSpeed); currentScore = 0; UpdateGameStatus(); // Draw the snake DrawSnake(); // snakeFood = null; GameArea.Children.Remove(snakeFood); //DrawSnakeFood(); DrawSnakeFood(); bdrWelcomeMessage.Visibility = Visibility.Collapsed; bdrHighscoreList.Visibility = Visibility.Collapsed; bdrEndOfGame.Visibility = Visibility.Collapsed; // Go! gameTickTimer.IsEnabled = true; }
/// <summary> /// Clear the game area and start a new game /// </summary> private void StartNewGame() { // Remove potential dead snake parts and leftover food... foreach (SnakePart snakeBodyPart in snakeParts) { if (snakeBodyPart.UiElement != null) { GameArea.Children.Remove(snakeBodyPart.UiElement); } } snakeParts.Clear(); if (snakeFood != null) { GameArea.Children.Remove(snakeFood); } // Close any open windows bdrWelcomeMessage.Visibility = Visibility.Collapsed; bdrGameOver.Visibility = Visibility.Collapsed; bdrHighscoreList.Visibility = Visibility.Collapsed; // Initialize game settings currentScore = 0; snakeLength = SnakeStartLength; snakeDirection = SnakeDirection.Right; snakeParts.Add(new SnakePart(new Point(SnakeSquareSize * 5, SnakeSquareSize * 5), true)); gameTickTimer.Interval = TimeSpan.FromMilliseconds(SnakeStartSpeed); // Draw the elements and start game DrawSnake(); DrawSnakeFood(); gameTickTimer.IsEnabled = true; UpdateGameStatus(); }
private static async void HandleConsoleInputAsync() { await Task.Yield(); while (true) { ConsoleKey handledKey = Console.ReadKey().Key; SnakeDirection newDirection = direction; switch (handledKey) { case ConsoleKey.UpArrow: newDirection = SnakeDirection.Back; break; case ConsoleKey.DownArrow: newDirection = SnakeDirection.Forward; break; case ConsoleKey.RightArrow: newDirection = SnakeDirection.Right; break; case ConsoleKey.LeftArrow: newDirection = SnakeDirection.Left; break; } if (newDirection != direction) { direction = newDirection; } } }
public void ChangeSnakeDirection(SnakeDirection direction) { switch (SnakeObj.SnakeDirection) { case SnakeDirection.Right: if (direction != SnakeDirection.Left) { SnakeObj.SnakeDirection = direction; } break; case SnakeDirection.Down: if (direction != SnakeDirection.Up) { SnakeObj.SnakeDirection = direction; } break; case SnakeDirection.Left: if (direction != SnakeDirection.Right) { SnakeObj.SnakeDirection = direction; } break; case SnakeDirection.Up: if (direction != SnakeDirection.Down) { SnakeObj.SnakeDirection = direction; } break; } }
// Use this for initialization void Start() { SnakeDirection snakeDirection = this.GetComponent <SnakeDirection>(); smooth = snakeDirection.smooth; bodyPart = new List <Transform>(); }
void SetRandomDirection() { // int dirRandom = Random.Range (0, (int) SnakeDirection.COUNT); int dirStart = 2; // Start from right direction direction = (SnakeDirection)dirStart; }
public static float ToRadius(this SnakeDirection snakeDirection) { float rotation = 0f; switch (snakeDirection) { case SnakeDirection.Up: rotation = (float)(180 * Math.PI / 180); break; case SnakeDirection.Right: rotation = (float)(270 * Math.PI / 180); break; case SnakeDirection.Down: rotation = 0f; break; case SnakeDirection.Left: rotation = (float)(90 * Math.PI / 180); break; } return(rotation); }
private static Point[] GetEyesPoints(Point point, SnakeDirection direction) { Point TopLeft() => new Point(point.X + 1, point.Y + 1); Point TopRight() => new Point(point.X + 7, point.Y + 1); Point BottomLeft() => new Point(point.X + 1, point.Y + 7); Point BottomRight() => new Point(point.X + 7, point.Y + 7); if (direction == SnakeDirection.Up) { return new[] { TopLeft(), TopRight() } } ; if (direction == SnakeDirection.Down) { return new[] { BottomLeft(), BottomRight() } } ; if (direction == SnakeDirection.Left) { return new[] { TopLeft(), BottomLeft() } } ; return(new[] { TopRight(), BottomRight() }); } } }
//Find the Next Movement Loaction But Not Move It internal Point PeekNextLoaction([OptionalAttribute] SnakeDirection peekDir /* =SnakeDirection.None */) { Point retPt = new Point(this.m_location.X, this.m_location.Y); if (peekDir == SnakeDirection.None) { peekDir = m_direction; } switch (peekDir) { case SnakeDirection.Left: retPt.X -= this.m_increment; return(retPt); case SnakeDirection.Right: retPt.X += this.m_increment; return(retPt); case SnakeDirection.Up: retPt.Y -= this.m_increment; return(retPt); case SnakeDirection.Down: retPt.Y += this.m_increment; return(retPt); } return(retPt); }
private PositionOnBoard GetLocationForNewPart(SnakeDirection snakeDirection) { var location = Last.Location; var newLocation = new PositionOnBoard(location.PosLeftCanvas, location.PosTopCanvas); switch (snakeDirection) { case SnakeDirection.Up: newLocation.PosTopCanvas += 22; break; case SnakeDirection.Right: newLocation.PosLeftCanvas -= 22; break; case SnakeDirection.Down: newLocation.PosTopCanvas -= 22; break; case SnakeDirection.Left: newLocation.PosLeftCanvas += 22; break; } return(newLocation); }
private void Initialize() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { board[i, j] = new Cell(); //new Cell(false, true); board[i, j].Val = 0; //DrawRect(i, j, step, offsetX, offsetY, board[i, j].Food, board[i, j].Free); } } //GenerateFood((int)level.easy); //Console.WriteLine("Level: {0} with number {1}", level.easy, (int)level.easy); board[3, 3].Food = true; board[3, 3].Val = -1;// -1 dla jedzenia //board[8, 5].Head = true; headPosition = new Point(2, 0); board[2, 0].Val = 1; // glowa board[1, 0].Val = 2; board[0, 0].Val = 3; board[2, 0].Free = false; board[1, 0].Free = false; board[0, 0].Free = false; snakeDirection = SnakeDirection.Right; last_segment = 3; // bo patrz wyzej }
public void MoveBody(SnakeDirection snakeDirection) { for (int i = SnakeBodyParts.Count - 1; i > 0; i--) { var nextBodyPart = SnakeBodyParts[i - 1].Location; SnakeBodyParts[i].Location = new PositionOnBoard(nextBodyPart.PosLeftCanvas, nextBodyPart.PosTopCanvas); } switch (snakeDirection) { case SnakeDirection.Up: Head.Location.PosTopCanvas -= SnakeSpeed; break; case SnakeDirection.Right: Head.Location.PosLeftCanvas += SnakeSpeed; break; case SnakeDirection.Down: Head.Location.PosTopCanvas += SnakeSpeed; break; case SnakeDirection.Left: Head.Location.PosLeftCanvas -= SnakeSpeed; break; default: throw new Exception("Direction Unknown"); } }
private void UpdateEyes(Point point, SnakeDirection direction) { var eye1 = new Ellipse { Width = 2, Height = 2, Fill = new SolidColorBrush(Colors.Black) }; var eye2 = new Ellipse { Width = 2, Height = 2, Fill = new SolidColorBrush(Colors.Black) }; var points = GetEyesPoints(point, direction); var point1 = points[0]; var point2 = points[1]; Canvas.SetTop(eye1, point1.Y); Canvas.SetLeft(eye1, point1.X); Canvas.SetZIndex(eye1, 1); Canvas.SetTop(eye2, point2.Y); Canvas.SetLeft(eye2, point2.X); Canvas.SetZIndex(eye2, 1); eyes[0] = eye1; eyes[1] = eye2; }
public void Rotate(SnakeRotation direction) { const int numOfDirections = (int)SnakeDirection.Total; int ch = direction == SnakeRotation.Clockwise ? 1 : numOfDirections - 1; _direction = (SnakeDirection)((int)(_direction + ch) % numOfDirections); }
public Snake(SnakeDirection direction, int x, int y, int size = 10) { this.size = size; Add(new SnakePiece(direction, x, y, size)); Grow(); //Start with a tail... to make movement simpler }
private void StartNewGame() { bdrWelcomeMessage.Visibility = Visibility.Collapsed; bdrHighscoreList.Visibility = Visibility.Collapsed; bdrEndOfGame.Visibility = Visibility.Collapsed; foreach (SnakePart snakeBodyPart in snakeParts) { if (snakeBodyPart.UiElement != null) { GameArea.Children.Remove(snakeBodyPart.UiElement); } } snakeParts.Clear(); if (snakeFood != null) { GameArea.Children.Remove(snakeFood); } currentScore = 0; snakeLength = SnakeStartLength; snakeDirection = SnakeDirection.Right; snakeParts.Add(new SnakePart() { Position = new Point(SnakeSquareSize * 5, SnakeSquareSize * 5) }); gameTickTimer.Interval = TimeSpan.FromMilliseconds(SnakeStartSpeed); DrawSnake(); DrawSnakeFood(); UpdateGameStatus(); gameTickTimer.IsEnabled = true; }
public SnakeSection GetNeighbor(SnakeDirection direction) { int deltaX = 0; int deltaY = 0; switch (direction) { case SnakeDirection.Up: deltaY = -1; break; case SnakeDirection.Down: deltaY = 1; break; case SnakeDirection.Left: deltaX = -1; break; case SnakeDirection.Right: deltaX = 1; break; } return(new SnakeSection(X + deltaX, Y + deltaY)); }
//Move The snake based on the current direction internal void Move(SnakeDirection moveDir /* = SnakeDirection.None */) { if (moveDir == SnakeDirection.None) { moveDir = this.m_direction; } switch (moveDir) { case SnakeDirection.Left: this.m_location.X -= this.m_increment; return; case SnakeDirection.Right: this.m_location.X += this.m_increment; return; case SnakeDirection.Up: this.m_location.Y -= this.m_increment; return; case SnakeDirection.Down: this.m_location.Y += this.m_increment; return; } }
public void DirectionChangesIfDoneToProperDirection(SnakeDirection current, SnakeDirection next) { // act var directionAfter = _uut.GetNewDirectionIfChanged(current, next); // assert Assert.AreEqual(next, directionAfter); }
public void NoDirectionChangeIfDirectionTheSame(SnakeDirection current, SnakeDirection nextButSame) { // act var directionAfter = _uut.GetNewDirectionIfChanged(current, nextButSame); // assert Assert.AreEqual(current, directionAfter); }
public Snake(int startX, int startY, int length) { positon = new Coord(startX, startY); this.length = length; direction = SnakeDirection.RIGHT; tail = new Queue <Coord>(); tail.Enqueue(positon.Clone()); }
public void NoDirectionChangeIfNewDirectionIsOpposite(SnakeDirection current, SnakeDirection opposite) { // act var directionAfter = _uut.GetNewDirectionIfChanged(current, opposite); // assert Assert.AreEqual(current, directionAfter); }
public SnakeDirection GetNextDirection(SnakeDirection currentDirection, int foodX, int foodY) { if (currentDirection == SnakeDirection.Up && _myHeadPosition.Y < _wallDistanceThreshold) { return(SnakeDirection.Left); } if (currentDirection == SnakeDirection.Right && _myHeadPosition.X > _width - _wallDistanceThreshold) { return(SnakeDirection.Up); } if (currentDirection == SnakeDirection.Down && _myHeadPosition.Y > _width - _wallDistanceThreshold) { return(SnakeDirection.Right); } if (currentDirection == SnakeDirection.Left && _myHeadPosition.X < _wallDistanceThreshold) { return(SnakeDirection.Down); } if ((currentDirection == SnakeDirection.Down && _myHeadPosition.Y >= foodY) || (currentDirection == SnakeDirection.Up && _myHeadPosition.Y <= foodY)) { if (_myHeadPosition.X > foodX) { return(SnakeDirection.Left); } if (_myHeadPosition.X < foodX) { return(SnakeDirection.Right); } } if ((currentDirection == SnakeDirection.Right && _myHeadPosition.X >= foodX) || (currentDirection == SnakeDirection.Left && _myHeadPosition.X <= foodX)) { if (_myHeadPosition.Y > foodY) { return(SnakeDirection.Up); } if (_myHeadPosition.Y < foodY) { return(SnakeDirection.Down); } } return(currentDirection); }
public override void OnStart(QGetContent get) { sprite = new QSprite(this, "snakeHead"); CurrentDir = SnakeDirection.Down; Coroutine.Start(SnakeMove()); fruit = GetBehavior <Fruit>("Fruit"); Scene.SpriteRenderer.ClearColor = QColor.Black; }
public void ResetParam(Point point) { SnakeLength = SnakeStartLength; Direction = SnakeDirection.Right; SnakeParts.Add(new SnakePart() { Position = point }); }
//Based on user input, change the direction the snake should move. Cannot be backwards. public void ChangeDirection(ConsoleKey moveKey) { if (moveKey == ConsoleKey.UpArrow && Direction != SnakeDirection.Down) Direction = SnakeDirection.Up; else if (moveKey == ConsoleKey.RightArrow && Direction != SnakeDirection.Left) Direction = SnakeDirection.Right; else if (moveKey == ConsoleKey.DownArrow && Direction != SnakeDirection.Up) Direction = SnakeDirection.Down; else if (moveKey == ConsoleKey.LeftArrow && Direction != SnakeDirection.Right) Direction = SnakeDirection.Left; }
public Snake(Point startPosition, SnakeDirection startDirection, ConsoleColor backgroundColor, ConsoleColor snakeColor) { _body = new List<Point>(); _removePoints = new List<Point>(); _addPoints = new List<Point>(); _head = startPosition; _direction = startDirection; _backgroundColor = backgroundColor; _addPoints.Add(_head); _snakeColor = snakeColor; }
private const short DefaultSnakeLength = 4; //Start size of the snake #endregion Fields #region Constructors public Snake() { //Setting snake's start direction and placing all the snake parts Direction = SnakeDirection.Down; Position.X = 10; Position.Y = 10; NewHeadPosition = new Position(Position.X, Position.Y); for (var i = 0; i < DefaultSnakeLength; i++) { SnakeElements.Add(new Position (Position.X, Position.Y)); } }
public void ChangeDirection(SnakeDirection direction) { //Do not allow direct reversals if (direction == SnakeDirection.Up && _direction == SnakeDirection.Down) return; if (direction == SnakeDirection.Down && _direction == SnakeDirection.Up) return; if (direction == SnakeDirection.Left && _direction == SnakeDirection.Right) return; if (direction == SnakeDirection.Right && _direction == SnakeDirection.Left) return; _direction = direction; }
/// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } SnakeDirection oldDirection = snakeDirection; Vector2 oldSnakePosition = snakePosition; bool justInitialized = false; // Get keyboard input KeyboardState state = Keyboard.GetState(); if (IsKeyReleased(Keys.Space, state)) { TogglePaused(); } if (IsKeyReleased(Keys.R, state)) { InitializeSnake(); justInitialized = true; } if (!paused && !justInitialized) { if (state.IsKeyDown(Keys.Left)) { if (snakeDirection != SnakeDirection.Right) { snakeDirection = SnakeDirection.Left; } } if (state.IsKeyDown(Keys.Right)) { if (snakeDirection != SnakeDirection.Left) { snakeDirection = SnakeDirection.Right; } } if (state.IsKeyDown(Keys.Up)) { if (snakeDirection != SnakeDirection.Down) { snakeDirection = SnakeDirection.Up; } } if (state.IsKeyDown(Keys.Down)) { if (snakeDirection != SnakeDirection.Up) { snakeDirection = SnakeDirection.Down; } } } if (IsKeyReleased(Keys.G, state)) { GrowSnake(); } if (state.IsKeyDown(Keys.OemPlus)) { snakeSpeed += 5; } if (state.IsKeyDown(Keys.OemMinus)) { snakeSpeed -= 5; if (snakeSpeed < 0) { snakeSpeed = 0; } } if (state.IsKeyDown(Keys.OemCloseBrackets)) { snakeLength += 1.0f; } if (state.IsKeyDown(Keys.OemOpenBrackets)) { snakeLength -= 1.0f; if (snakeLength < initialSnakeLength) { snakeLength = initialSnakeLength; } } if (state.IsKeyDown(Keys.W)) { cameraPitch += 1.0f; if (cameraPitch > 360.0f) { cameraPitch -= 360.0f; } UpdateViewMatrix(); } if (state.IsKeyDown(Keys.S)) { cameraPitch -= 1.0f; if (cameraPitch < 0) { cameraPitch += 360.0f; } UpdateViewMatrix(); } if (state.IsKeyDown(Keys.D)) { cameraDistance += 1.0f; UpdateViewMatrix(); } if (state.IsKeyDown(Keys.A)) { cameraDistance -= 1.0f; if (cameraDistance < 0) { cameraDistance = 0; } UpdateViewMatrix(); } if (IsKeyReleased(Keys.V, state)) { if (cameraType == CameraType.FromAbove) { SetCameraType(CameraType.Angled); } else { SetCameraType(CameraType.FromAbove); } } if (IsKeyReleased(Keys.T, state)) { Toggle2DSnake(); } if (IsKeyReleased(Keys.I, state)) { ToggleOverlay(); } if (IsKeyReleased(Keys.C, state)) { ToggleIgnoreCollisions(); } if (IsKeyReleased(Keys.B, state)) { if (arenaBoundaryType == ArenaBoundaryType.WrapAround) { arenaBoundaryType = ArenaBoundaryType.Collision; } else if (arenaBoundaryType == ArenaBoundaryType.Collision) { arenaBoundaryType = ArenaBoundaryType.NoBoundary; } else { arenaBoundaryType = ArenaBoundaryType.WrapAround; } } if (state.IsKeyDown(Keys.Q) || state.IsKeyDown(Keys.Escape)) { Exit(); } oldKeyboardState = state; if (!paused && !justInitialized) { // Check if snake switched direction if (snakeDirection != oldDirection) { // Add position to list of joints snakePositions.Add(new Vector2(oldSnakePosition.X, oldSnakePosition.Y)); disconnectedToPreviousPoint.Add(false); } // Move the snake float displacement = (float)gameTime.ElapsedGameTime.TotalSeconds * snakeSpeed; switch (snakeDirection) { case SnakeDirection.Up: snakePosition.Y -= displacement; break; case SnakeDirection.Down: snakePosition.Y += displacement; break; case SnakeDirection.Left: snakePosition.X -= displacement; break; case SnakeDirection.Right: snakePosition.X += displacement; break; } bool hit = false; // Check if snake went out of bounds if (arenaBoundaryType == ArenaBoundaryType.Collision) { if (snakePosition.X < 0 || snakePosition.X > graphics.GraphicsDevice.Viewport.Width - 1 || snakePosition.Y < 0 || snakePosition.Y > graphics.GraphicsDevice.Viewport.Height - 1) { hit = true; } } else if (arenaBoundaryType == ArenaBoundaryType.WrapAround) { if (snakePosition.X < 0) { oldSnakePosition = new Vector2(graphics.GraphicsDevice.Viewport.Width, snakePosition.Y); snakePositions.Add(new Vector2(0, snakePosition.Y)); disconnectedToPreviousPoint.Add(false); snakePositions.Add(oldSnakePosition); disconnectedToPreviousPoint.Add(true); snakePosition = new Vector2(graphics.GraphicsDevice.Viewport.Width + snakePosition.X, snakePosition.Y); } else if (snakePosition.X > graphics.GraphicsDevice.Viewport.Width) { oldSnakePosition = new Vector2(0, snakePosition.Y); snakePositions.Add(new Vector2(graphics.GraphicsDevice.Viewport.Width, snakePosition.Y)); disconnectedToPreviousPoint.Add(false); snakePositions.Add(oldSnakePosition); disconnectedToPreviousPoint.Add(true); snakePosition = new Vector2(snakePosition.X - graphics.GraphicsDevice.Viewport.Width, snakePosition.Y); } else if (snakePosition.Y < 0) { oldSnakePosition = new Vector2(snakePosition.X, graphics.GraphicsDevice.Viewport.Height); snakePositions.Add(new Vector2(snakePosition.X, 0)); disconnectedToPreviousPoint.Add(false); snakePositions.Add(oldSnakePosition); disconnectedToPreviousPoint.Add(true); snakePosition = new Vector2(snakePosition.X, graphics.GraphicsDevice.Viewport.Height + snakePosition.Y); } else if (snakePosition.Y > graphics.GraphicsDevice.Viewport.Height) { oldSnakePosition = new Vector2(snakePosition.X, 0); snakePositions.Add(new Vector2(snakePosition.X, graphics.GraphicsDevice.Viewport.Height)); disconnectedToPreviousPoint.Add(false); snakePositions.Add(oldSnakePosition); disconnectedToPreviousPoint.Add(true); snakePosition = new Vector2(snakePosition.X, snakePosition.Y - graphics.GraphicsDevice.Viewport.Height); } } // Trim the snake tail, making sure the length of the snake is correct. // Go backwards from current point through each point, adding up the displacement. // Stop when you reach the right length, removing history of non relevant points. float length = 0; Vector2 lastPosition = snakePosition; Vector2 vector = new Vector2(); int i; for (i = snakePositions.Count - 1; i >= 0 && length <= snakeLength; --i) { Vector2 position = snakePositions[i]; if (i == snakePositions.Count - 1 || !disconnectedToPreviousPoint[i + 1]) { vector = lastPosition - position; length += vector.Length(); } lastPosition = position; } if (length > snakeLength) { // Modify the tail end position float changeAmount = length - snakeLength; vector.Normalize(); vector = vector * changeAmount; Vector2 newPosition = snakePositions[i + 1] + vector; snakePositions[i + 1] = newPosition; } if (i >= 0) { snakePositions.RemoveRange(0, i + 1); disconnectedToPreviousPoint.RemoveRange(0, i + 1); // Make sure the first element (the tail end point) is set to false disconnectedToPreviousPoint[0] = false; } // Check if snake intersected with itself LineSegment2 recentMovement = new LineSegment2(oldSnakePosition, snakePosition); if (!hit && !ignoreSnakeCollisions) { if (snakePositions.Count > 1) { lastPosition = snakePositions[snakePositions.Count - 2]; i = snakePositions.Count - 3; for (; i >= 0 && !hit; --i) { Vector2 position = snakePositions[i]; LineSegment2 snakeSegment = new LineSegment2(position, lastPosition); if (!disconnectedToPreviousPoint[i + 1]) { hit = LineSegment2.SegmentsIntersect(recentMovement, snakeSegment); } lastPosition = position; } } } if (hit) { InitializeSnake(); } else { // Check if snake reached a goal if (LineSegment2.SegmentsIntersect(recentMovement, goalLeftSide) || LineSegment2.SegmentsIntersect(recentMovement, goalRightSide) || LineSegment2.SegmentsIntersect(recentMovement, goalBottomSide) || LineSegment2.SegmentsIntersect(recentMovement, goalLeftSide)) { // intersection GrowSnake(); RepositionGoal(); } Update3DSnakeData(); } } base.Update(gameTime); }
/// <summary> /// Make a small snake and set a goal position. /// </summary> private void InitializeSnake() { snakePosition = new Vector2(200.0f, 200.0f); snakeDirection = SnakeDirection.Right; snakeLength = initialSnakeLength; snakePositions.Clear(); disconnectedToPreviousPoint.Clear(); snakePositions.Add(new Vector2(snakePosition.X - snakeLength, snakePosition.Y)); disconnectedToPreviousPoint.Add(false); paused = false; Update3DSnakeData(); RepositionGoal(); }