用户在javascript中正确后如何禁用变量

时间:2018-07-27 15:45:53

标签: javascript

因此,我正在制作一个小游戏,用户在连接时说“命中”时,用户必须猜测正确的网格。 3次命中后,您沉没了“船”。没什么特别的,但是我想知道的是:当用户正确时如何禁用变量(或使其无效)?例如:var x = 5;,用户输入5,因此应该是正确的。但是,如果您再按两次5(命中次数将为3),它将使我的船沉没,而您不会猜测其他2个网格。所以我的问题是:如何disable一个变量?

let isSunk = false;
let guess;
let location1 = Math.floor(Math.random() * 10);
let location2 = Math.floor(Math.random() * 10);
let location3 = Math.floor(Math.random() * 10);
let guesses = 0;
let hit = 0;



while (isSunk == false) {
    guess = prompt("Try to sink me!");

    guesses += 1;

    if (guess == location1 || guess == location2 || guess == location3) {
        hit += 1;
        window.alert("HIT!");
    } else {
        window.alert("MISS!");
    }

    if (hit == 3) {
        window.alert("you sunk my ship!");
        isSunk = true;
    }
}

2 个答案:

答案 0 :(得分:0)

不是在顶部声明您的位置,而是在while循环中声明它们,因此,无论何时执行循环,它都会为您提供新的数字,因此用户无法猜测。

答案 1 :(得分:0)

考虑修改您的问题解决方法。不允许用户输入相同的值。

let isSunk = false;
let guess;
let location1 = Math.floor(Math.random() * 10);
let location2 = Math.floor(Math.random() * 10);
let location3 = Math.floor(Math.random() * 10);
let guesses = 0;
let hit = 0;

//Add array of past guesses
let userGuesses = [];

while (isSunk == false) {
  guess = prompt("Try to sink me!");

  guesses += 1;

  //Check array of past guesses
  if (userGuesses.indexOf(guess) > -1) {
    window.alert("YOU ALREADY TRIED THAT!");
  } else if (guess == location1 || guess == location2 || guess == location3) {
    hit += 1;
    window.alert("HIT!");
  } else {
    window.alert("MISS!");
  }

  if (hit == 3) {
    window.alert("you sunk my ship!");
    isSunk = true;
  }

  //Add guess to array of past guesses
  userGuesses.push(guess);
}