public void DirectRover(int roverId, RoverOperationType operationType) { Rover rover; if (!Rovers.TryGetValue(roverId, out rover)) { throw new InvalidOperationException("Rover does not exist"); } if (operationType == RoverOperationType.RotateLeft || operationType == RoverOperationType.RotateRight) { rover.Heading = GetNewHeading(rover.Heading, operationType); } else if (operationType == RoverOperationType.Move) { var newPosition = Vector.Add(rover.Position, rover.Heading); if (newPosition.X < 0 || newPosition.X > PlateauLength || newPosition.Z < 0 || newPosition.Z > PlateauWidth) { throw new InvalidOperationException("Rover has driven off the plateau"); } foreach (var roverEntry in Rovers.Values) { if (Vector.AreEqual(roverEntry.Position, newPosition)) { throw new InvalidOperationException("Collision! Curiousity got the best of this Martian rover"); } } rover.Position = newPosition; } }
private static Vector GetNewHeading(Vector heading, RoverOperationType operationType) { if (operationType != RoverOperationType.RotateLeft && operationType != RoverOperationType.RotateRight) { return(heading); } var theta = DegreeToRadian(operationType == RoverOperationType.RotateRight ? -90 : 90); var cs = Math.Cos(theta); var sn = Math.Sin(theta); var newX = heading.X * cs - heading.Z * sn; var newY = heading.X * sn + heading.Z * cs; return(new Vector() { X = (int)Math.Round(newX), Z = (int)Math.Round(newY) }); }