我想在JS中製作hang子手遊戲。我有以下功能工作。計算機顯示我的數組中的隨機單詞。我打印按下屏幕上的按鍵,並在用戶鬆動之前給用戶10個按鍵。我遇到的問題是讓數組顯示在var possibleWord部分,因此它顯示爲空格或破折號。提前謝謝你的幫助。如何在JS中製作Hang子手遊戲
//Computer picks random word to guess
function getItem() {
//Possible words to guess
var words = ['jason', 'kaitlyn', 'lora', 'matthew'];
document.getElementById("wordGuess").innerHTML = words[Math.floor(Math.random() * words.length)];
//Displays possible words blank spaces
var possibleWord = "J A S O N";
var blankSpaces = "";
var wordLength = possibleWord.length;
for (i = 0; i < wordLength; i++) {
var x = possibleWord.charAt(i);
if (x === " " || x === "/'") {
blankSpaces += x;
} else {
blankSpaces += "_";
}
}
document.getElementById("blankSpaces").innerHTML = blankSpaces;
}
//This code captures the keypress and prints it out on the screen
var guessesLeft = 9;
document.onkeypress = function(keyPressed) {
var keyPressed = keyPressed || window.event,
charCode = keyPressed.keyCode || keyPressed.which,
lettersGuessed = String.fromCharCode(charCode);
// var userGuess = prompt("What word do you guess?");
// var userGuess = words.split('');
// var userGuess
// if (words.indexOf(userGuess) > -1) {
// \t alert("Your guess is correct.")
// }else {
// \t alert("Your guess is wrong.")
// }
document.getElementById("lettersGuessed").innerHTML += lettersGuessed;
document.getElementById("guessesLeft").innerHTML = guessesLeft;
guessesLeft--;
if (guessesLeft === -1) {
alert("You Loose!");
}
}
<body onload="getItem()">
<div class="wrapper">
<div class="container">
Press any key to get started!
<br>
<br>Wins: # of times user guessed the word correctly
<br>
<br>Display random word from Array: <strong><u><span id="wordGuess"></span></u></strong>
<br>
<br>as the user guesses the correct letter, make the word display like this: <span id="blankSpaces"></span>
<br>
<br>Number of Guesses Remaining: <span id="guessesLeft">10</span>
<br>
<br>Letters Already Guessed: <span id="lettersGuessed"></span>
<br>
<br>
</div>
</div>
</body>
它是什麼目前正在做什麼,你期望它做什麼? – Harangue
它目前顯示我在possibleWord變量空間中放置的任何單詞的空格。我希望能用我創建的數組生成的隨機詞填充。 –