我正在用JavaScript制作战舰用于学校项目而且我被困住了。
计算机随机生成船只,用户必须通过输入坐标来尝试下沉所有计算机的船只。船上的命中保存在一个阵列中。该阵列包含零以表示船的长度(因此长度为4的船具有4个零的阵列)。当船被击中时,0变为1.如果所有元素都是1,则船沉没。问题是我的代码注册了命中,但只有当你用长度为4的船时才将它放在一个数组中。
任何人都可以帮助我吗?以下是code of the "game"本身:
function game() {
inputArray = [4, 3, 2];
var boats = randomBoats(inputArray);
var currentBoat = 0;
var sunkenBoat = 0;
var numberOfTurns = 0;
while (sunkenBoat !== inputArray.length) {
var hit = false;
var target = "(" + prompt("Enter targetcoordinate (x,y)") + ")";
var targetString = target.replace(/\s+/g, '');
for (var i = 0; i !== inputArray.length; i++) {
for (var j = 0; j !== boats[i].usedPositions().length; j++) {
console.log(targetString)
if (targetString === boats[i].usedPositions()[j].toString()) {
raak = true;
boats[i].hits[j] = 1;
console.log(boats[i].hits);
currentBoat = boats[i];
} else {
currentBoat = boats[i];
}
}
}
console.log(currentBoat.hits);
console.log(allEquals(currentBoat.hits, 1));
if (hit)
alert("Hit!");
else
alert("Miss!");
if (allEquals(currentBoat.hits, 1)) {
alert("Boat with length " + currentBoat.hits.length + " has sunken!");
sunkenBoat++;
}
numberOfTurns++
}
alert("You've won! You did it in " + numberOfTurns + " turns.")
}
答案 0 :(得分:1)
问题在于内循环中的else,因为你处理每个船(外循环)和所有位置(内循环)你的
else {
currentBoat = boats[i];
}
总是将当前船设置为最后一个[i];
当你发现命中时,你也不需要处理任何其他位置或船只,所以当你发现这样的命中时,请尽早打破:
raak = false;
for(var i = 0; i < inputArray.length && !raak; i++) {
for(var j = 0; j !== boats[i].usedPositions().length; j++) {
console.log(targetString)
if(targetString === boats[i].usedPositions()[j].toString()) {
raak = true;
boats[i].hits[j] = 1;
console.log(boats[i].hits);
currentBoat = boats[i];
break;
}
}
}