Hangman中的JavaScript增减值

时间:2018-08-17 23:40:58

标签: javascript

我正在用JavaScript,HTML和CSS制作一个Hangman游戏。在尝试正确猜出所有字母后,我一直努力使wins变量增加1,而在猜出每个字母后,使猜测值减少1。

我还认为我需要合并以下代码行,但是在我尝试插入的所有代码中,游戏都会中断:

// Set the inner HTML contents of the #game div to our html string
    document.querySelector(".container").innerHTML = html;

我的代码:

//Array of available words
    const words = ["patriots", "bills", "dolphins", "jets", "chiefs", "chargers", "raiders", "broncos", "steelers", "ravens", "bengals", "browns", "jaguars", "titans", "colts", "texans", "eagles", "cowboys", "redskins", "giants", "rams", "seahawks", "cardinals", "niners", "vikings", "lions", "packers", "bears", "saints", "panthers", "falcons", "buccaneers"];

   let currentWord;
   let dashes = [];
   let rightLetter = [];
   let wrongLetter = [];

// Creating variables to hold the number of wins and guesses remaining
    let wins = 0;
    let guesses = 10;

// Creating a variable to hold our new HTML. Our HTML now keeps track of the user and computer guesses, and wins/losses/ties.
    let html =
    "<p>wins: " + wins + "</p>" +
    "<p>guesses: " + guesses + "</p>";



//Click button to start game
    document.getElementById("start").addEventListener("click",function(){
        startGame("")
    })

//Computer chooses a random word from the words array. The random choice becomes currentWord
    function startGame(){
        currentWord = words[Math.floor(Math.random() * words.length)];


//Creates underscores depending on length of the currentWord; push underscores to dashes array 
        for ( let i = 0; i < currentWord.length; i++ ) {
            dashes.push(' _ ');


        }

        writeWordDashes(dashes.join(' '))
    }

    function writeWordDashes(str){
        document.querySelector("#dashContainer").innerHTML = str;
    }


//HTML document waits for key to be pressed; key is assiged Unicode value (a/A are diff)
        document.addEventListener('keypress', (event) => {
            let codes = event.keyCode;

//Convert a Unicode value into a character
            let characters = String.fromCharCode(codes);

//Search currentWord for the users correct guess; push character to rightLetter array
            if(currentWord.indexOf(characters) > -1)
            rightLetter.push(characters);


//Replace dashes with correctly choosen characters
            dashes[currentWord.indexOf(characters)] = characters;

//Loop over word and replace dashes
            for( let i = 0; i < currentWord.length; i++) {
                let currentLetter = currentWord[i];
            if (currentLetter === characters) {
                dashes[i] = characters;
            }
        }

//Write words to dashes
            writeWordDashes (dashes.join(''))


//Search currentWord for the users incorrect guess; push character to wrongLetter array
            if(currentWord.indexOf(characters) < 0)
            wrongLetter.push(characters);

            document.querySelector(".wrong").innerHTML = wrongLetter;   
            })

1 个答案:

答案 0 :(得分:0)

-编辑-

因此,对我的所作所为/原因做了一些解释。

如果可能,应避免创建带有字符串连接的html。在您的情况下,您应该事先创建html元素,然后通过document.getElementById('wins')或document.querySelector('wins')填充它们,这很有意义。 如果您坚持要保留当前的实现,则需要将.container放在某个地方(...),但是随后每次需要更新容器时,内容都会发生相关变化(可能封装函数中),最有可能的更新将是猜测部分。

接下来,由于游戏需要增加获胜变量,因此需要有一个获胜场景。为此,我们需要一个新变量,该变量说明游戏是否处于活动状态(否则您可以继续赢/输)。 每按一次键,都会做出一个猜测。每次猜测都会检查,也许这场比赛已经赢了。在这种情况下,请检查破折号是否包含“ _”,如果没有,则返回-1并赢得比赛。 每次击键都会检查单词中是否包含字母。如果不是,则猜测增加。未来版本还可以在结束游戏之前提供固定数目的猜测。

-编辑-

<button id="start">Start</button>
<div id="dashContainer"></div>
<div class="wrong"></div>
wins <div id="wins"></div>
losses <div id="losses"></div>
guesses <div id="guesses"></div>


<script>
  //Array of available words
  const words = ["patriots", "bills", "dolphins", "jets", "chiefs", "chargers", "raiders", "broncos", "steelers", "ravens", "bengals", "browns", "jaguars", "titans", "colts", "texans", "eagles", "cowboys", "redskins", "giants", "rams", "seahawks", "cardinals", "niners", "vikings", "lions", "packers", "bears", "saints", "panthers", "falcons", "buccaneers"];

  let currentWord;
  let dashes = [];
  let rightLetter = [];
  let wrongLetter = [];
  let gameActive = false;

  // Creating variables to hold the number of wins and guesses remaining
  let wins = 0;
  let losses = 0;
  let guesses = 0;

  // Creating a variable to hold our new HTML. Our HTML now keeps track of the user and computer guesses, and wins/losses/ties.
  function render() {
    document.querySelector('#wins').textContent = wins;
    document.querySelector('#losses').textContent = losses;
    document.querySelector('#guesses').textContent = guesses;
  }
  render();


  //Click button to start game
  document.getElementById("start").addEventListener("click", function() {
    startGame("")

  })

  function checkWin() {
    if (!gameActive) return;

    if (dashes.indexOf(' _ ') < 0) {
      gameActive = false;
      wins += 1;
    }
  }

  //Computer chooses a random word from the words array. The random choice becomes currentWord
  function startGame() {
    gameActive = true;
    currentWord = words[Math.floor(Math.random() * words.length)];
    wrongLetter = [];
    rightLetter = [];
    guesses = 0;
    dashes = [];
    //Creates underscores depending on length of the currentWord; push underscores to dashes array
    for (let i = 0; i < currentWord.length; i++) {
      dashes.push(' _ ');
    }

    writeWordDashes(dashes.join(' '))
  }

  function writeWordDashes(str) {
    document.querySelector("#dashContainer").innerHTML = str;
  }


  //HTML document waits for key to be pressed; key is assiged Unicode value (a/A are diff)
  document.addEventListener('keypress', (event) => {
    if (!gameActive) return;
    let codes = event.keyCode;

    //Convert a Unicode value into a character
    let characters = String.fromCharCode(codes);

    //Search currentWord for the users correct guess; push character to rightLetter array
    if (currentWord.indexOf(characters) > -1)
      rightLetter.push(characters);


    //Replace dashes with correctly choosen characters
    dashes[currentWord.indexOf(characters)] = characters;

    //Loop over word and replace dashes
    for (let i = 0; i < currentWord.length; i++) {
      let currentLetter = currentWord[i];
      if (currentLetter === characters) {
        dashes[i] = characters;
      }
    }

    //Write words to dashes
    writeWordDashes(dashes.join(''))


    //Search currentWord for the users incorrect guess; push character to wrongLetter array
    if (currentWord.indexOf(characters) < 0) {
      if (wrongLetter.indexOf(characters) < 0) {
        wrongLetter.push(characters);
        guesses += 1;
      }
    }
    document.querySelector(".wrong").innerHTML = wrongLetter;
    checkWin();
    render();
  })
</script>