/// <summary> /// Executes a command. /// </summary> /// <param name="command">The command to be executed.</param> public void Execute(Command command) { switch(command) { case Command.MoveForward: if (Orientation == Orientation.North) Y++; else if (Orientation == Orientation.East) X++; else if (Orientation == Orientation.South) Y--; else X--; break; case Command.TurnLeft: if ((int)Orientation == 0) Orientation = (Orientation)3; else Orientation = (Orientation)((int)Orientation - 1); break; case Command.TurnRight: if ((int)Orientation == 3) Orientation = (Orientation)0; else Orientation = (Orientation)((int)Orientation + 1); break; } }
public Message Move(Command command, bool[,] map) { switch (command) { case Command.l: case Command.r:{ turnLeftOrRight(command); return new Message(true, this._x, this._y); } case Command.f: case Command.b:{ int[] nextXY = this.calcNextPos(command); //if (nextXY[0] < 0 || nextXY[0] >= 100 || nextXY[1] < 0 || nextXY[1] >= 100) // return false; if (nextXY[0] < 0) nextXY[0] = 99; if (nextXY[0] >= 100) nextXY[0] = 0; if (nextXY[1] < 0) nextXY[1] = 99; if (nextXY[1] >= 100) nextXY[1] = 0; if (map[nextXY[0], nextXY[1]]) return new Message(false, nextXY[0], nextXY[1]); this._x = nextXY[0]; this._y = nextXY[1]; return new Message(true, nextXY[0], nextXY[1]); } default: return new Message(true, this._x, this._y); } }
private int[] calcNextPos(Command command) { if(command==Command.l || command==Command.r) return new int[]{this._x,this._y}; int nextX = this._x; int nextY = this._y; if(command==Command.f){ switch(this._direction){ case Direction.North: nextX++; break; case Direction.South: nextX--; break; case Direction.West: nextY--; break; case Direction.East: nextY++; break; } }else{ switch(this._direction){ case Direction.North: nextX--; break; case Direction.South: nextX++; break; case Direction.West: nextY++; break; case Direction.East: nextY--; break; } } return new int[]{nextX, nextY}; }
private bool turnLeftOrRight(Command command) { if (command == Command.f || command == Command.b) return false; int increase = 1; if (command == Command.l) increase = -1; int direction = (int)this._direction + increase; if (direction == -1) direction = 3; if (direction == 4) direction = 0; this._direction = (Direction)direction; return true; }