我正在使用 JavaScript 开发火星到漫游车程序,并且我已经完成了迭代 1,该迭代允许我的漫游车向二维 (x,y) 的所有方向移动。现在是迭代#2,我需要能够向流动站发送一系列命令并按顺序执行它们。
请告诉我一些关于如何进行迭代 2 的见解。
这是我当前的代码:
// --------- Mars Rover Kata: Iteration #1 ------------ \\
// ------------------- User Experience using Console --------- \\
var promptSay = "Play with the Console!\nW = UP \nS = DOWN \nD = RIGHT \nA = LEFT";
var gridEdge = "You can\'go there! \n\nPlease notice that you are playing with an imaginary grid and the farest you can go is 9 steps";
var wrongInput = "---WRONG INPUT!--- Please use a correct input i. e. : \nW = UP \nS = DOWN \nD = RIGHT \nA = LEFT";
// Object Definition: (Vars inside a Var , may have functions) \\
var AJRover = {
position : [0, 0],
invalidInput: function(notright) { // Notification for invalid Input
alert(notright);
this.move(prompt(wrongInput));
},
invalidKey: function(message) { // Notification if you reach grid's edge
alert(message);
this.move(prompt(promptSay));
},
move: function(moveRover) { //Directions
switch(moveRover.toLowerCase()) {
case 'w':
this.goDirection("up");
break;
case 's':
this.goDirection("down");
break;
case 'd':
this.goDirection("right");
break;
case 'a':
this.goDirection('left');
break;
default:
this.invalidInput(wrongInput);
}
},
goDirection: function(direction) { //Directions Functions
switch(direction) {
case 'up':
if (this.position[1] >= -9 && (this.position[1] + 1) <= 9) {
this.position[1]++;
break;
} else {
this.invalidKey(gridEdge);
break;
}
case 'down':
if (this.position[1] <= 9 && (this.position[1] -1 ) >= -9) { // this needs to go back and stop at -9
this.position[1]--;
break;
} else {
this.invalidKey(gridEdge);
break;
}
case 'right':
if (this.position[0] >= -9 && (this.position[0] + 1) <= 9) {
this.position[0]++;
break;
} else {
this.invalidKey(gridEdge);
break;
}
case 'left':
if (this.position[0] <= 9 && (this.position[0] -1) >= -9) {
this.position[0]--;
break;
} else {
this.invalidKey(gridEdge);
break;
}
}
}
};
// ---- object END ----- \\\
// 1- This function calls the object move (this.move)
// 2- Sends the alert to prompts the var promptSay
// 3- Expects input to decide the output
while (true) { //This code block allows user move the rover on mars by interacting with console
var entry = prompt(promptSay);
AJRover.move(entry);
console.log('You are now at position: ', AJRover.position);
}
最佳答案
在浏览环境中,这不能通过与控制台交互来完成。
您所要做的就是利用事件监听器。以下是如何通过将它们绑定(bind)到文档正文来完成此操作的示例。
const W_KEY = 119;
const A_KEY = 97;
const S_KEY = 115;
const D_KEY = 100;
document.body.addEventListener("keypress", function(e) {
let entry = null;
switch(e.keyCode) {
case W_KEY:
entry = "w";
break;
case A_KEY:
entry = "a";
break;
case S_KEY:
entry = "s";
break;
case D_KEY:
entry = "d";
break;
}
if(entry) {
console.log("Key " + entry + " was pressed!");
AJRover.move(key);
}
}
关于javascript - JavaScript 上的火星到漫游者。我需要能够向流动站发出一系列命令并按顺序执行它们。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41958786/