private void lengthenSnake() { //Make deep copy of end body segment BodySegment endBodySegment = bodySegments[bodySegments.Count - 1]; BodySegment newEndBodySegment = endBodySegment.deepCopy(); //Modify deep copy's coordinates and distance till next turn if (endBodySegment.goingUp) { newEndBodySegment.y += 20; } else if (endBodySegment.goingDown) { newEndBodySegment.y -= 20; } else if (endBodySegment.goingLeft) { newEndBodySegment.x += 20; } else if (endBodySegment.goingRight) { newEndBodySegment.x -= 20; } //Add new body segment to list of body segments if snake is not lined up perfectly if (endBodySegment.distancesTillTurns.Count != 0) { newEndBodySegment.distancesTillTurns[0] += 20; } bodySegments.Add(newEndBodySegment); }
//Description: Returns deep copy of calling body segment. public BodySegment deepCopy() { //Determine which way calling body segment is going and then tell copy to move same way direction dir = direction.L; if (goingUp) { dir = direction.U; } else if (goingDown) { dir = direction.D; } else if (goingLeft) { dir = direction.L; } else if (goingRight) { dir = direction.R; } BodySegment deepCopyOfBodySegment = new BodySegment(x, y, l, bodySegmentColor, dir); if (distancesTillTurns.Count != 0) { for (int i = 0; i < distancesTillTurns.Count; i++) { deepCopyOfBodySegment.distancesTillTurns.Add(distancesTillTurns[i]); } } if (waysToTurn.Count != 0) { foreach (direction d in waysToTurn) { deepCopyOfBodySegment.waysToTurn.Enqueue(d); } } return(deepCopyOfBodySegment); }
public void updateGame() { //Update snake snakeHead.update(); if (appleCollidesWithSnakeHead()) { //When the snake head collides with an apple while (appleCollidesWithSnakeHead() || appleCollidesWithBodyOfSnake() || appleIsToCloseToSnakeHead()) { apple = new Apple(foregroundColor); growSnake = true; } } //Snake grows if player just hit an apple if (growSnake) { biteSoundEffect.Play(); lengthenSnake(); growSnake = false; ++playerScore; } //If a cover collides with the last body segment, stop drawing it. BodySegment lastBodySegment = bodySegments[bodySegments.Count() - 1]; for (int i = 0; i < covers.Count; ++i) { if (covers[i].collides(lastBodySegment.x, lastBodySegment.y)) { covers.RemoveAt(i); } } //Update all the body segments for (int i = 0; i < bodySegments.Count; ++i) { bodySegments[i].update(); } }