问题描述
我必须在10x10的假想板上移动流动站。一切进展顺利,直到在给我错误时在moveForward(和moveBackward)函数上设置了if语句。在使用if条件的情况下,播放器不应移动到网格之外,因为会出现一条错误消息,在我的情况下为msg:您不能将流动站放置在板外!
let myRover = {
direction: 'N',x: 0,y: 0,travelLog: [{
x: 0,y: 0
}]
}
function turnLeft(rover) {
console.log('turnLeft was called!');
switch (rover.direction) {
case 'W':
rover.direction = 'S';
break;
case 'N':
rover.direction = 'W';
break;
case 'S':
rover.direction = 'E';
break;
case 'E':
rover.direction = 'N';
break;
}
}
function turnRight(rover) {
console.log('turnRight was called!');
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) {
console.log('moveForward was called');
if (rover.x >= 0 && rover.x < 9 && rover.y >= 0 && rover.y < 9) {
switch (rover.direction) {
case 'N':
rover.x++;
break;
case 'W':
rover.y--;
break;
case 'S':
rover.x--;
break;
case 'E':
rover.y++;
break;
}
} else {
console.log(''You cannot place the rover outside the board!'');
}
}
//print out rover position
console.log(`The rover has position: x= ${rover.x},y= ${rover.y};`)
//declare a new variable in order to update and push the new position into our roverObject
let newPosition = {
x: rover.x,y: rover.y
};
rover.travelLog.push(newPosition);
function moveBackward(rover) {
console.log('moveBackward was called');
if (rover.x >= 0 && rover.x < 9 && rover.y >= 0 && rover.y < 9) {
switch (rover.direction) {
case 'N':
rover.x--;
break;
case 'W':
rover.y++;
break;
case 'S':
rover.x++;
break;
case 'E':
rover.y--;
break;
}
} else {
console.log(''You cannot place the rover outside the board!'');
check }
rover.travelLog.push(newPosition);
}
//print out rover position
console.log(`The rover has position: x= ${rover.x},y= ${rover.y};`)
//create a function that receives a list of commands (what the rover should do when we give it certain commands)
function command(rover,orders) {
for (let i = 0; i < orders.length; i++) {
let order = orders[i];
switch (order) {
case 'f':
moveForward(rover,order);
break;
case 'r':
turnRight(rover,order);
break;
case 'l':
turnLeft(rover,order);
break;
case 'b':
moveBackward(rover,order);
break;
/*BONUS 3// If we enter a letter into our input that is not one of the rover commands,nothing will happen
// check default:
// check continue; */
}
}
console.log(`The rover path was: ${rover.travelLog});
}
解决方法
您的if语句当前正在检查当前位置,则应改为检查流动站的未来位置。例如:
function moveBackward(rover) {
console.log('moveBackward was called');
let future_x = rover.x
let future_y = rover.y
switch (rover.direction) {
case 'N':
future_x--;
break;
case 'W':
future_y++;
break;
case 'S':
future_x++;
break;
case 'E':
future_y--;
break;
}
if (future_x >= 0 && future_x <= 9 && future_y >= 0 && future_y <= 9) {
rover.x = future_x
rover.y = future_y
rover.travelLog.push(newPosition);
} else {
console.log("You cannot place the rover outside the board!");
}
}