我正在构建一个游戏,我希望从提示中获取玩家的输入,并将其与他们已经使用的输入进行比较,如果他们两次选择相同的内容,则拒绝该选择。这是我的相关代码:
var playerChoiceRow = 0;
var playerChoiceColumn = 0;
var playerAttackArray = [];
function playerAttack(playerChoiceRow,playerChoiceColumn) {
for (var i=0; i<playerAttackArray.length; i++){
if ([playerChoiceRow,playerChoiceColumn] === playerAttackArray[i]){
alert("You have already attacked this space, please choose another.");
playerChoiceRow = prompt("Please choose a number between 0 and 5.");
playerChoiceColumn = prompt("Please choose a number between 0 and 5.");
}
}
if (playerChoiceRow === undefined){
alert("Please choose a number between 0 and 5!");
playerChoiceRow = prompt("Please choose a number between 0 and 5.");
}
if (playerChoiceColumn === undefined){
alert("Please choose a number between 0 and 5!");
playerChoiceColumn = prompt("Please choose a number between 0 and 5.");
}
playerAttackArray.push([playerChoiceRow,playerChoiceColumn]);
while (playerCounter || computerCounter <=4){
var playerChoiceRow = prompt("Please select row of attack. (0 though 5)")-'';
var playerChoiceColumn = prompt("Please select column of attack. (0 though 5)")-'';
playerAttack(playerChoiceRow,playerChoiceColumn);
if (playerCounter == 5){
alert("You have sunk all enemy boats!");
break;
}
}
在Javascript数组中,比较是关于身份,而不是内容;换句话说===
,当两个表达式是数组时,两个表达式之间的返回值仅在它们引用同一数组对象时才返回true,而不是在两个包含相同事物的数组中返回。
您可以通过首先将两面都转换为字符串来解决此问题:
if (""+[playerChoiceRow,playerChoiceColumn] === ""+playerAttackArray[i]) ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句