REFACTOR: introduce Direction enum and extract wrapping logic
This commit is contained in:
parent
7632401aa4
commit
bb868d8dd6
1 changed files with 43 additions and 28 deletions
|
|
@ -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 {
|
||||
int x;
|
||||
int y;
|
||||
String direction;
|
||||
Direction _direction;
|
||||
final int plateauWidth;
|
||||
final int plateauHeight;
|
||||
|
||||
Rover({
|
||||
required this.x,
|
||||
required this.y,
|
||||
required this.direction,
|
||||
required String direction,
|
||||
this.plateauWidth = 100,
|
||||
this.plateauHeight = 100,
|
||||
});
|
||||
}) : _direction = Direction.fromCode(direction);
|
||||
|
||||
String get direction => _direction.code;
|
||||
|
||||
void turnLeft() {
|
||||
const leftTurns = {
|
||||
'N': 'W',
|
||||
'W': 'S',
|
||||
'S': 'E',
|
||||
'E': 'N',
|
||||
};
|
||||
direction = leftTurns[direction]!;
|
||||
_direction = _direction.turnLeft();
|
||||
}
|
||||
|
||||
void turnRight() {
|
||||
const rightTurns = {
|
||||
'N': 'E',
|
||||
'E': 'S',
|
||||
'S': 'W',
|
||||
'W': 'N',
|
||||
};
|
||||
direction = rightTurns[direction]!;
|
||||
_direction = _direction.turnRight();
|
||||
}
|
||||
|
||||
void moveForward() {
|
||||
switch (direction) {
|
||||
case 'N':
|
||||
y = (y + 1) % (plateauHeight + 1);
|
||||
switch (_direction) {
|
||||
case Direction.north:
|
||||
y = _wrapCoordinate(y + 1, plateauHeight);
|
||||
break;
|
||||
case 'E':
|
||||
x = (x + 1) % (plateauWidth + 1);
|
||||
case Direction.east:
|
||||
x = _wrapCoordinate(x + 1, plateauWidth);
|
||||
break;
|
||||
case 'S':
|
||||
y = (y - 1) % (plateauHeight + 1);
|
||||
if (y < 0) y += plateauHeight + 1;
|
||||
case Direction.south:
|
||||
y = _wrapCoordinate(y - 1, plateauHeight);
|
||||
break;
|
||||
case 'W':
|
||||
x = (x - 1) % (plateauWidth + 1);
|
||||
if (x < 0) x += plateauWidth + 1;
|
||||
case Direction.west:
|
||||
x = _wrapCoordinate(x - 1, plateauWidth);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int _wrapCoordinate(int value, int max) {
|
||||
final wrapped = value % (max + 1);
|
||||
return wrapped < 0 ? wrapped + max + 1 : wrapped;
|
||||
}
|
||||
|
||||
void execute(String commands) {
|
||||
for (var i = 0; i < commands.length; i++) {
|
||||
final command = commands[i];
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue