61 lines
1 KiB
Dart
61 lines
1 KiB
Dart
class Rover {
|
|
int x;
|
|
int y;
|
|
String direction;
|
|
|
|
Rover({required this.x, required this.y, required this.direction});
|
|
|
|
void turnLeft() {
|
|
const leftTurns = {
|
|
'N': 'W',
|
|
'W': 'S',
|
|
'S': 'E',
|
|
'E': 'N',
|
|
};
|
|
direction = leftTurns[direction]!;
|
|
}
|
|
|
|
void turnRight() {
|
|
const rightTurns = {
|
|
'N': 'E',
|
|
'E': 'S',
|
|
'S': 'W',
|
|
'W': 'N',
|
|
};
|
|
direction = rightTurns[direction]!;
|
|
}
|
|
|
|
void moveForward() {
|
|
switch (direction) {
|
|
case 'N':
|
|
y += 1;
|
|
break;
|
|
case 'E':
|
|
x += 1;
|
|
break;
|
|
case 'S':
|
|
y -= 1;
|
|
break;
|
|
case 'W':
|
|
x -= 1;
|
|
break;
|
|
}
|
|
}
|
|
|
|
void execute(String commands) {
|
|
for (var i = 0; i < commands.length; i++) {
|
|
final command = commands[i];
|
|
switch (command) {
|
|
case 'L':
|
|
turnLeft();
|
|
break;
|
|
case 'R':
|
|
turnRight();
|
|
break;
|
|
case 'M':
|
|
moveForward();
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|