tdd-katas/lib/mars_rover.dart

71 lines
1.3 KiB
Dart

class Rover {
int x;
int y;
String direction;
final int plateauWidth;
final int plateauHeight;
Rover({
required this.x,
required this.y,
required this.direction,
this.plateauWidth = 100,
this.plateauHeight = 100,
});
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 = (y + 1) % (plateauHeight + 1);
break;
case 'E':
x = (x + 1) % (plateauWidth + 1);
break;
case 'S':
y = (y - 1) % (plateauHeight + 1);
if (y < 0) y += plateauHeight + 1;
break;
case 'W':
x = (x - 1) % (plateauWidth + 1);
if (x < 0) x += plateauWidth + 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;
}
}
}
}