我用javascript做了一个简单的战舰游戏,但是没有正确的workimg。我将位置放在数组中,并尝试使用splice方法从该数组中删除猜测的位置。但是它会警告“ MISS!”当我输入0到6之间的任何数字时。
编辑:我通过使用parseInt方法进行提示来解决了这个问题。
var location1 = Math.floor(Math.random() * 5);
var location2 = location1 + 1;
var location3 = location2 + 1;
var locations = [];
locations.push([location1, location2, location3]);
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = prompt("Enter your guess(0 - 6)");
if (guess < 0 || guess > 6) {
alert("Please enter a valid number!");
} else {
guesses++;
if (locations.indexOf(guess) > 0) {
locations.splice(locations.indexOf(guess), 1);
hits++;
alert("HIT!");
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS!");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, which
means your shooting accuracy was " + (3 / guesses);
alert(stats);
答案 0 :(得分:0)
做一件事创建具有类似元素的数组
var location=[1,2,3,4,5]
,而不是从中删除数组delete元素的索引