代码之家  ›  专栏  ›  技术社区  ›  JackJack

构建一个命运之轮游戏,我正在尝试让按键事件检测随机单词数组中的字母

  •  0
  • JackJack  · 技术社区  · 8 年前

    我正在做一个命运之轮游戏,从一个数组中选择一个随机单词。我在游戏函数下面创建了一个函数,用于从a-z屏幕上显示的字母列表中检测按下的键。我的问题是,在按下playgame()按钮后,Randomword()函数被激发之前,我无法让游戏检测到按下的键。我正在尝试让用户在buttonPress()函数中按下字母,以匹配wordchoice.length循环中的字母,并在屏幕上显示出字母的位置,然后在字母被使用后将其排除。我尝试创建letterclicked变量并使其全局化,以便playgame()函数可以访问它,但我没有任何运气匹配用户选择的字母和play按钮上方显示框中的字母。我在这里做错什么了?我在randomword()函数中尝试了控制台日志记录,但只有在您单击Play并基本上重置游戏后,才会检测到按键。下面是我的代码。谢谢你的帮助!

    <DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <title>Wheel of Fortune</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="stylesheet" href="main.css">
    
        </head>
        <body>
        <body>
            <div id="container">
                <div id="header">
                    <p class="welcome">Welcome to Wheel of Fortune!</p>
                    <!-- The letters will be tied to the number of letters in the random array -->
                    <p class="letters">There are <span id="numbers">0</span> letters in this word</p>
                    <!-- The user will be given a number of choices and with each wrong choice, they lose a turn -->
                    <p class="lives">You have <span id="guesses">0</span> guesses left</p>
    
                    <span id="words"></span><br>
    
                    <button id="play" onclick="playGame()">Play</button>
    
                </div>
                <div id="alphabet" onclick="buttonPress(event)">
                    <button>A</button>
                    <button>B</button>
                    <button>C</button>
                    <button>D</button>
                    <button>E</button>
                    <button>F</button>
                    <button>G</button>
                    <button>H</button>
                    <button>I</button>
                    <button>J</button>
                    <button>K</button>
                    <button>L</button>
                    <button>M</button>
                    <br>
                    <button>N</button>
                    <button>O</button>
                    <button>P</button>
                    <button>Q</button>
                    <button>R</button>
                    <button>S</button>
                    <button>T</button>
                    <button>U</button>
                    <button>V</button>
                    <button>W</button>
                    <button>X</button>
                    <button>Y</button>
                    <button>Z</button>
                </div>
    
                <span id="your-guess">You guessed </span>
            </div>
    
            <script src="main.js"></script>
        </body>
        </html>
    
        body {
        margin: 0 auto;
        width: 1000px;
        font-size: 20px;
        background: url("http://res.cloudinary.com/angelrodriguez/image/upload/c_crop,h_624/v1534810805/wheeloffortune.jpg");
        background-size: cover;
        color: white;
    }
    
    #header {
        margin: 20px;
    }
    
    #alphabet {
        margin: 20px;
    }
    
    button {
        border: 2px solid blue;
        font-size: 20px;
    }
    
    #words {
        font-size: 30px;
        margin: 10px;
        letter-spacing: 20px;
    }
    
    #play {
        margin: 20px;
    }
    
    
    
    
    // 3. Quit the game if the player wants to.
    // 5. Keep track of letters the player has guessed.
    // 6. Show the player their progress.
    // 7. Finish when the player has guessed the word.
    
    // Create global variables
    let gameOver = false;
    var guessesLeft = 6;
    var letterClicked;
    var wordArray = ["JAVASCRIPT", "ARRAYS", "FUNCTIONS", "HOISTING", "RECURSION", "EVENTS", "KEYUP", "TERNARY"];
    // 1. Pick a random word.
    
    
    
    //Start a new game
    function playGame() {
        newGame.addEventListener("click", function() {
            //fire the randomWord function to generate a new word
            randomWord();
        })
    }
    
    // Pass the letter event from buttonPress into the randomWord function
    function randomWord(letter) {
        var answerList = [];
        // console.log(answerList);
        // letterGuessed = "";
        console.log(letterClicked);
        var wordChoice = wordArray[Math.floor(Math.random() * wordArray.length)];tbw
    
        var wordSplit = wordChoice.split('');
        // console.log(wordSplit);
    
        for (var i = 0; i < wordSplit.length; i++) {
            answerList[i] = "_";
        }
    
        // if the letter is in the word
        // Update the players progress with the guess
        for (var z = 0; z < wordChoice.length; z++) {
            if (wordChoice[z] === letterClicked) {
                letterClicked = answerList[i];
                // answerList[i].innerHTML = letterGuessed;
            }
        }
    
        //Display underscores on page representing each word in the random word
        wordDisplay.innerHTML = answerList;
    
        //Display number of letters in the random word on the page
        var remainingLetters = wordChoice.length;
        letterCount.innerHTML = "The word is " + remainingLetters + 
        " letters long";
    
    }
    
    // 2. Take the player’s guess.
    function buttonPress(e) { 
        letterClicked = e.target.textContent;
        document.getElementById("your-guess").innerHTML = "You guessed the letter " + letterClicked;
    
        //fix issue with clicking divs
    }
    
    
    // If the player wants to quite the game {
    //     Quit the game
    // }
    
    
    // Grab elements
    var numbers = document.querySelector("#numbers");
    var guesses = document.querySelector("#guesses");
    var wordDisplay = document.querySelector("#words");
    var letterCount = document.querySelector(".letters");
    var newGame = document.querySelector("#play");
    var letterBoxes = document.querySelector("#alphabet");
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   ya.ymer    8 年前

    收到一封信 buttonPress 你可以使用 e.toElement.textContent .

    我做了一些解决方案,但我认为这不是一个很好的例子。

    let words = [ "TERNARY"], guessesLeft, chosenWord;
    
    let getRandomWord = words => {
      return words[Math.floor(Math.random()*words.length)];
    }, updateGuesses = count => {
      guesses.innerText = count;
      guessesLeft = count;
    }, updateWords = word => {
       document.getElementById('words').innerHTML = word; 
    }, hideAlphabet = () => alphabet.style.display = 'none',
       setGameStatus = status => document.getElementById("status").innerHTML = status;
    
    play.addEventListener('click', e => {
      e.target.style.display = 'none'; // hide when game started.
      alphabet.style.display = 'block';
      chosenWord = getRandomWord(words);
      updateGuesses(chosenWord.length);
      updateWords(String("*").repeat(chosenWord.length))
    });
    
    alphabet.addEventListener('click', e => {
      let letter = e.toElement.textContent;
      
      e.toElement.disabled = true;
      
      if (!new RegExp(letter).test(chosenWord)) {
         updateGuesses(guessesLeft -1);
      } else {
         let newString = document.getElementById('words').innerHTML.split(''), indexesOfALetter = [];
         
         for(let i = 0; i < chosenWord.length; i += 1) // here for is a fastest way. 
             if (chosenWord[i] === letter) indexesOfALetter.push(i);
         
         indexesOfALetter.forEach(i => newString[i] = letter); 
         
         updateWords(newString.join(''));
      }
      
      if (!/\*/.test(document.getElementById('words').innerHTML)) {
         hideAlphabet();
         setGameStatus("Congratulations! You won that game");
      }
      
      if (guessesLeft < 1) {
        hideAlphabet();
        setGameStatus("Unfortunately, you lost the game ;(");
        updateWords(chosenWord);
      }
      
    });
    body {
        margin: 0 auto;
        width: 1000px;
        font-size: 20px;
       
        color: black;
    }
    
    #header {
        margin: 20px;
    }
    
    #alphabet {
        display: none;
        margin: 20px;
    }
    
    button {
        border: 2px solid blue;
        font-size: 20px;
    }
    
    #words {
        font-size: 30px;
        margin: 10px;
        letter-spacing: 20px;
    }
    
    #play {
        margin: 20px;
    }
    <div id="container">
        <div id="header">
            <p class="welcome">Welcome to Wheel of Fortune!</p>
            <!-- The user will be given a number of choices and with each wrong choice, they lose a turn -->
            <p class="lives">You have <span id="guesses">0</span> guesses left</p>
    
            <span id="words"></span><br>
    
            <button id="play">Play</button>
    
        </div>
        <div id="alphabet">
            <button>A</button>
            <button>B</button>
            <button>C</button>
            <button>D</button>
            <button>E</button>
            <button>F</button>
            <button>G</button>
            <button>H</button>
            <button>I</button>
            <button>J</button>
            <button>K</button>
            <button>L</button>
            <button>M</button>
            <br>
            <button>N</button>
            <button>O</button>
            <button>P</button>
            <button>Q</button>
            <button>R</button>
            <button>S</button>
            <button>T</button>
            <button>U</button>
            <button>V</button>
            <button>W</button>
            <button>X</button>
            <button>Y</button>
            <button>Z</button>
        </div>
    
        <span id="status"></span>
    </div>
    推荐文章