Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

robot route #1271

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/main/java/core/basesyntax/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package core.basesyntax;

import java.util.Random;

public class Main {
public static void main(String[] args) {
Random random = new Random();
Robot robot = new Robot(Direction.UP, 0, 0);
RobotRoute route = new RobotRoute();

int toX = random.nextInt(21) - 10;
int toY = random.nextInt(21) - 10;

route.moveRobot(robot, toX, toY);

System.out.println("Starting position: " + robot);
System.out.println("Target coordinates: (" + toX + ", " + toY + ")");
System.out.println("After moving: " + robot);
}
}
34 changes: 33 additions & 1 deletion src/main/java/core/basesyntax/RobotRoute.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,38 @@

public class RobotRoute {
public void moveRobot(Robot robot, int toX, int toY) {
//write your solution here
//write your solution here
int currentX = robot.getX();
int currentY = robot.getY();

if (toX > currentX) {
turnToDirection(robot, Direction.RIGHT);
while (robot.getX() < toX) {
robot.stepForward();
}
} else if (toX < currentX) {
turnToDirection(robot, Direction.LEFT);
while (robot.getX() > toX) {
robot.stepForward();
}
}
if (toY > currentY) {
turnToDirection(robot, Direction.UP);
while (robot.getY() < toY) {
robot.stepForward();
}
} else if (toY < currentY) {
turnToDirection(robot, Direction.DOWN);
while (robot.getY() > toY) {
robot.stepForward();
}
}
}

private void turnToDirection(Robot robot, Direction targetDirection) {
while (robot.getDirection() != targetDirection) {
robot.turnLeft();
robot.turnRight();
}
}
}
Loading