我试图添加一个按钮,所以当我单击它时,代码(游戏)从头开始

时间:2018-09-13 05:47:48

标签: javascript

<!DOCTYPE html>
 <html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Hangman Test</title>
     <link rel="stylesheet" type="text/css" href="assets/css/style.css">
  </head>
  <body>
    <div class="mainDiv">
        <button type="button" id="startButton">Start Game</button>
        <!-- This is where the blank word will be displayed -->
        <div id="city-text"></div>
        <div id="wins-guesses">
            <h2 id="wins-num"></h2>
            <h2 id="guesses-num"></h2>
        </div>

        <div id="letters-guessed"></div>
       </div>
      <script src="assets/javascript/game.js"></script>
   </body>
</html>   
    var secretWord = [];
    var underScoreWord = [];
    var wins = 0;
    var guessesRemaining = 15;
    var alreadyGuessed = [];
    var wordLetter = false;

    //Assign HTML elements to variables
    var cityText = document.getElementById("city-text");
    var winsNum = document.getElementById("wins-num");
    var guessesNum = document.getElementById("guesses-num")
    var lettersGuessed = document.getElementById("letters-guessed")


    //Array of cities
    var city = ["PARIS", "WELLINGTON", "HANOI", "PERTH", "MARSEILLE", "LONDON", "OTTAWA", "ZURICH", "BOSTON", "TOKYO", "DETROIT", "LIVERPOOL"];

    //console.log(city);
    //Pick random word from the team array and push the result to an empty array. 
    function pickRandomCity() {
        var randomCity = city[Math.floor(Math.random() * city.length)];
        secretWord = randomCity.split('');
        return randomCity;
    }

    var cityPicked = pickRandomCity();
    //Get length of secretWord and push as underscores to am empty array
    for (var i = 0; i < cityPicked.length; i++) {
        underScoreWord.push("_");

    }

    console.log('secretWord : ' + secretWord);
    // console.log('underScoreWord : ' + underScoreWord);
    // console.log('------------------');
    // console.log('cityPicked : ' + cityPicked);



    //Check for letters
    //Listen for key press and check to see if its a match
    var guessedLetters = {};
    document.onkeyup = function letterCheck(event) {
        var userGuess = event.key;
        if (!guessedLetters[userGuess.toUpperCase()]) { // check if user pressed this key
            alreadyGuessed.push(userGuess.toUpperCase());
            guessedLetters[userGuess.toUpperCase()] = true;
            guessesRemaining--;

        } else { // this key has been pressed before, don't do anything
            return;
        }
        secretWord.map((n, i) => {
            if (userGuess.toUpperCase() === n.toUpperCase()) {
                underScoreWord[i] = n;
            }
        })

        console.log("Already guessed: " + alreadyGuessed);
        lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
        // Write to page
        cityText.textContent = underScoreWord.join(" ");
        winsNum.textContent = ("Wins: " + wins);
        guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
        console.log(underScoreWord);

        //    Change counter
        if (guessesRemaining === 0) {
            cityText.textContent = ("You lose");
        }

        if (secretWord.toString() === underScoreWord.toString()) {
            cityText.textContent = ("You win");
            wins++;
        }

    }
    console.log(underScoreWord);

我正在尝试添加按钮。因此,当我单击它时,游戏将从头开始-所有数字都会刷新,并且隐藏的单词已准备好被猜测。我猜对了整个单词就做到了。它会添加获胜++ ,如果猜测数变为,则会显示一条消息,提示“您输了”

我正在尝试使其全部连接,因此我可以随时按下按钮以再次开始游戏。  如何做到?

1 个答案:

答案 0 :(得分:1)

有一个简单的解决方案,将您拥有的所有内容包装在一个函数中,然后在单击该按钮时调用该函数。在运行按钮时也请禁用该按钮,并在游戏结束时将其启用。还要清除文本。
另一个解决方案是只重置每个变量和文本。

var wins = 0;
function newGame(){
  document.querySelector("#startButton").disabled = true;
  var secretWord = [];
  var underScoreWord = [];
  var guessesRemaining = 15;
  var alreadyGuessed = [];
  var wordLetter = false;

  //Assign HTML elements to variables
  var cityText = document.getElementById("city-text");
  var winsNum = document.getElementById("wins-num");
  var guessesNum = document.getElementById("guesses-num");
  var lettersGuessed = document.getElementById("letters-guessed");
  lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
  guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);

  //Array of cities
  var city = ["PARIS", "WELLINGTON", "HANOI", "PERTH", "MARSEILLE", "LONDON", "OTTAWA", "ZURICH", "BOSTON", "TOKYO", "DETROIT", "LIVERPOOL"];

  //console.log(city);

  //Pick random word from the team array and push the result to an empty array. 
  function pickRandomCity() {
    var randomCity = city[Math.floor(Math.random() * city.length)];
    secretWord = randomCity.split('');
    return randomCity;
  }

  var cityPicked = pickRandomCity();

  //Get length of secretWord and push as underscores to am empty array
  for (var i = 0; i < cityPicked.length; i++) {
    underScoreWord.push("_");

  }
  cityText.textContent = underScoreWord.join(" ");
  console.log('secretWord : ' + secretWord);
  // console.log('underScoreWord : ' + underScoreWord);
  // console.log('------------------');
  // console.log('cityPicked : ' + cityPicked);



  //Check for letters
  //Listen for key press and check to see if its a match
  var guessedLetters = {};
  document.onkeyup = function letterCheck(event) {
    var userGuess = event.key;
    if (!guessedLetters[userGuess.toUpperCase()]) { // check if user pressed this key
      alreadyGuessed.push(userGuess.toUpperCase());
      guessedLetters[userGuess.toUpperCase()] = true;
      guessesRemaining--;

    } else { // this key has been pressed before, dont do anything
      return;
    }
    secretWord.map((n, i) => {
      if (userGuess.toUpperCase() === n.toUpperCase()) {
        underScoreWord[i] = n;
      }
    })

    console.log("Already guessed: " + alreadyGuessed);
    lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
    // Write to page
    cityText.textContent = underScoreWord.join(" ");
    guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
    console.log(underScoreWord);
    //    Change counter
    if (guessesRemaining === 0) {
      cityText.textContent = ("You lose");
      document.querySelector("#startButton").disabled = false;
    }
    if (secretWord.toString() === underScoreWord.toString()) {
      cityText.textContent = ("You win");
      wins++;
      winsNum.textContent = ("Wins: " + wins);
      document.querySelector("#startButton").disabled = false;
    }
  }
  console.log(underScoreWord);
}
newGame();
<div class="mainDiv">
  <button type="button" id="startButton" onclick="newGame()">Start Game</button>
  <!-- This is where the blank word will be displayed -->
  <div id="city-text"></div>
  <div id="wins-guesses">
    <h2 id="wins-num"></h2>
    <h2 id="guesses-num"></h2>
  </div>
  <div id="letters-guessed"></div>
</div>