REFACTOR: introduce Position and Plateau value objects
This commit is contained in:
parent
bb868d8dd6
commit
5ee4e1edc0
1 changed files with 48 additions and 28 deletions
|
|
@ -20,21 +20,53 @@ enum Direction {
|
|||
}
|
||||
}
|
||||
|
||||
class Position {
|
||||
final int x;
|
||||
final int y;
|
||||
|
||||
Position(this.x, this.y);
|
||||
|
||||
Position moveNorth() => Position(x, y + 1);
|
||||
Position moveEast() => Position(x + 1, y);
|
||||
Position moveSouth() => Position(x, y - 1);
|
||||
Position moveWest() => Position(x - 1, y);
|
||||
}
|
||||
|
||||
class Plateau {
|
||||
final int width;
|
||||
final int height;
|
||||
|
||||
Plateau(this.width, this.height);
|
||||
|
||||
Position wrap(Position position) {
|
||||
final wrappedX = _wrapCoordinate(position.x, width);
|
||||
final wrappedY = _wrapCoordinate(position.y, height);
|
||||
return Position(wrappedX, wrappedY);
|
||||
}
|
||||
|
||||
int _wrapCoordinate(int value, int max) {
|
||||
final wrapped = value % (max + 1);
|
||||
return wrapped < 0 ? wrapped + max + 1 : wrapped;
|
||||
}
|
||||
}
|
||||
|
||||
class Rover {
|
||||
int x;
|
||||
int y;
|
||||
Position _position;
|
||||
Direction _direction;
|
||||
final int plateauWidth;
|
||||
final int plateauHeight;
|
||||
final Plateau plateau;
|
||||
|
||||
Rover({
|
||||
required this.x,
|
||||
required this.y,
|
||||
required int x,
|
||||
required int y,
|
||||
required String direction,
|
||||
this.plateauWidth = 100,
|
||||
this.plateauHeight = 100,
|
||||
}) : _direction = Direction.fromCode(direction);
|
||||
int plateauWidth = 100,
|
||||
int plateauHeight = 100,
|
||||
}) : _position = Position(x, y),
|
||||
_direction = Direction.fromCode(direction),
|
||||
plateau = Plateau(plateauWidth, plateauHeight);
|
||||
|
||||
int get x => _position.x;
|
||||
int get y => _position.y;
|
||||
String get direction => _direction.code;
|
||||
|
||||
void turnLeft() {
|
||||
|
|
@ -46,25 +78,13 @@ class Rover {
|
|||
}
|
||||
|
||||
void moveForward() {
|
||||
switch (_direction) {
|
||||
case Direction.north:
|
||||
y = _wrapCoordinate(y + 1, plateauHeight);
|
||||
break;
|
||||
case Direction.east:
|
||||
x = _wrapCoordinate(x + 1, plateauWidth);
|
||||
break;
|
||||
case Direction.south:
|
||||
y = _wrapCoordinate(y - 1, plateauHeight);
|
||||
break;
|
||||
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;
|
||||
final newPosition = switch (_direction) {
|
||||
Direction.north => _position.moveNorth(),
|
||||
Direction.east => _position.moveEast(),
|
||||
Direction.south => _position.moveSouth(),
|
||||
Direction.west => _position.moveWest(),
|
||||
};
|
||||
_position = plateau.wrap(newPosition);
|
||||
}
|
||||
|
||||
void execute(String commands) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue