REFACTOR: introduce Direction enum and extract wrapping logic

This commit is contained in:
fiatcode 2026-02-24 10:50:39 +07:00
parent 7632401aa4
commit bb868d8dd6

View file

@ -1,57 +1,72 @@
enum Direction {
north('N'),
east('E'),
south('S'),
west('W');
final String code;
const Direction(this.code);
static Direction fromCode(String code) {
return Direction.values.firstWhere((d) => d.code == code);
}
Direction turnLeft() {
return Direction.values[(index + 3) % 4];
}
Direction turnRight() {
return Direction.values[(index + 1) % 4];
}
}
class Rover { class Rover {
int x; int x;
int y; int y;
String direction; Direction _direction;
final int plateauWidth; final int plateauWidth;
final int plateauHeight; final int plateauHeight;
Rover({ Rover({
required this.x, required this.x,
required this.y, required this.y,
required this.direction, required String direction,
this.plateauWidth = 100, this.plateauWidth = 100,
this.plateauHeight = 100, this.plateauHeight = 100,
}); }) : _direction = Direction.fromCode(direction);
String get direction => _direction.code;
void turnLeft() { void turnLeft() {
const leftTurns = { _direction = _direction.turnLeft();
'N': 'W',
'W': 'S',
'S': 'E',
'E': 'N',
};
direction = leftTurns[direction]!;
} }
void turnRight() { void turnRight() {
const rightTurns = { _direction = _direction.turnRight();
'N': 'E',
'E': 'S',
'S': 'W',
'W': 'N',
};
direction = rightTurns[direction]!;
} }
void moveForward() { void moveForward() {
switch (direction) { switch (_direction) {
case 'N': case Direction.north:
y = (y + 1) % (plateauHeight + 1); y = _wrapCoordinate(y + 1, plateauHeight);
break; break;
case 'E': case Direction.east:
x = (x + 1) % (plateauWidth + 1); x = _wrapCoordinate(x + 1, plateauWidth);
break; break;
case 'S': case Direction.south:
y = (y - 1) % (plateauHeight + 1); y = _wrapCoordinate(y - 1, plateauHeight);
if (y < 0) y += plateauHeight + 1;
break; break;
case 'W': case Direction.west:
x = (x - 1) % (plateauWidth + 1); x = _wrapCoordinate(x - 1, plateauWidth);
if (x < 0) x += plateauWidth + 1;
break; break;
} }
} }
int _wrapCoordinate(int value, int max) {
final wrapped = value % (max + 1);
return wrapped < 0 ? wrapped + max + 1 : wrapped;
}
void execute(String commands) { void execute(String commands) {
for (var i = 0; i < commands.length; i++) { for (var i = 0; i < commands.length; i++) {
final command = commands[i]; final command = commands[i];