-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule2.java
More file actions
102 lines (91 loc) · 2.91 KB
/
Copy pathmodule2.java
File metadata and controls
102 lines (91 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package Robot;
public class module2 {
public static void main(String[] args) {
Robot robot = new Robot(0, 0, Direction.UP);
moveRobot(robot, 10, 12);
}
public enum Direction {
UP,
DOWN,
LEFT,
RIGHT
}
public static class Robot {
int x;
int y;
Direction dir;
public Robot(int x, int y, Direction dir) {
this.x = x;
this.y = y;
this.dir = dir;
}
public Direction getDirection() { return dir; }
public int getX() { return x; }
public int getY() { return y; }
public void turnLeft() {
if (dir == Direction.UP) {
dir = Direction.LEFT;
} else if (dir == Direction.DOWN) {
dir = Direction.RIGHT;
} else if (dir == Direction.LEFT) {
dir = Direction.DOWN;
} else if (dir == Direction.RIGHT) {
dir = Direction.UP;
}
}
public void turnRight() {
if (dir == Direction.UP) {
dir = Direction.RIGHT;
} else if (dir == Direction.DOWN) {
dir = Direction.LEFT;
} else if (dir == Direction.LEFT) {
dir = Direction.UP;
} else if (dir == Direction.RIGHT) {
dir = Direction.DOWN;
}
}
public void stepForward() {
if (dir == Direction.UP) { y++; }
if (dir == Direction.DOWN) { y--; }
if (dir == Direction.LEFT) { x--; }
if (dir == Direction.RIGHT) { x++; }
}
}
public static void moveRobot(Robot robot, int toX, int toY) {
System.out.println("Координаты: x "
+ robot.getX() + ", y " + robot.getY());
int x = robot.getX();
int y = robot.getY();
System.out.println("Начальная позиция " + robot.getX() + " "
+ robot.getY() + ". Направление взгляда: " + robot.getDirection());
if (x >= toX) {
while (robot.getDirection() != Direction.LEFT) { robot.turnLeft(); }
while (x != toX) {
robot.stepForward();
x--; }
} else {
while (robot.getDirection() != Direction.RIGHT) { robot.turnRight(); }
while (x != toX) {
robot.stepForward();
x++;
}
}
if (y >= toY) {
while (robot.getDirection() != Direction.DOWN) {
robot.turnLeft();
}
while (y != toY) {
robot.stepForward();
y--;
}
} else {
while (robot.getDirection() != Direction.UP) {
robot.turnRight();
}
while (y != toY) {
robot.stepForward();
y++;
}
}
}
}