Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Rover Object Goes Here
- function Rover(){
- this.direction = "N";
- this.x = 0;
- this.y = 0;
- this.travelLog = [];
- }
- // ======================
- var commandsList = "rffrfflfrff";
- // ======================
- function reset(rover, grid){
- rover.direction = "N";
- rover.x = 0;
- rover.y = 0;
- rover.travelLog = [];
- grid = [];
- }
- function createGrid(grid){
- //creamos tabla
- for (var i = 0; i < 10; i++){
- grid[i] = new Array(9);
- for (var j = 0; j < 10; j++){
- grid[i][j] =" ";
- }
- }
- }
- grid[rover.y][rover.x] = rover.direction;
- function turnLeft(rover){
- switch (rover.direction) {
- case "N":
- rover.direction = "W";
- break;
- case "W":
- rover.direction = "S";
- break;
- case "S":
- rover.direction = "E";
- break;
- case "E":
- rover.direction = "N";
- break;
- }
- }
- function turnRight(rover){
- switch (rover.direction) {
- case "N":
- rover.direction = "E";
- break;
- case "W":
- rover.direction = "N";
- break;
- case "S":
- rover.direction = "W";
- break;
- case "E":
- rover.direction = "S";
- break;
- }
- }
- function moveForward(rover, grid){
- switch (rover.direction) {
- case "N":
- if (rover.y === 0) {
- console.log("MOVEMENT NOT ALLOWED!");
- }
- else {
- rover.y--;
- }
- break;
- case "W":
- if (rover.x === 0) {
- console.log("MOVEMENT NOT ALLOWED!");
- } else {
- rover.x--;
- }
- break;
- case "S":
- if (rover.y === 9) {
- console.log("MOVEMENT NOT ALLOWED!");
- } else {
- rover.y++;
- }
- break;
- case "E":
- if (rover.x === 9) {
- console.log("MOVEMENT NOT ALLOWED!");
- } else {
- rover.x++;
- }
- break;
- }
- }
- function commands(commandsList){
- var rover = new Rover();
- var grid = [];
- var commandsRegex = /[fbrl]+/i;
- var stringPosition = "";
- reset(rover, grid);
- createGrid(grid);
- createObstacles(grid, rover);
- console.log(grid.join("\n"));
- if ((commandsList.match(commandsRegex) === null) || (commandsList !== commandsList.match(commandsRegex)[0])) {
- console.log("THIS IS NOT A CORRECT LIST OF COMMANDS: inputs must be 'f', 'r', or 'l'");
- } else {
- for (var i = 0; i < commandsList.length; i++) {
- grid[rover.y][rover.x] = " ";
- switch (commandsList[i]) {
- case "f":
- console.log("moveForward was called");
- moveForward(rover, grid);
- break;
- case "r":
- console.log("turnRight was called!");
- turnRight(rover);
- break;
- case "l":
- console.log("turnLeft was called!");
- turnLeft(rover);
- break;
- }
- console.log("Current position and direction: (" + rover.x + ", " + rover.y + ", " + rover.direction +")");
- stringPosition = "\n\tCommand " + commandsList[i] + ": (" + rover.x + ", " + rover.y + ", " + rover.direction +")";
- rover.travelLog.push(stringPosition);
- grid[rover.y][rover.x] = rover.direction;
- console.log(grid.join("\n"));
- }
- console.log("TRACKING:" + rover.travelLog);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement