我的第一个真正的js程序。我正在创造经典的心灵游戏。我有一个带有js文件链接的html文件。问题:计算机总是选择相同的字母,就好像它被捕获在一个功能循环和“计算机”中一样。在赢或输之后,var不会被重新分配 - 它保持不变。 //已设置值 lettersIndex = [' a','',' c',' d',' e',&# 39; f','' h',' i',' j',' k&#39 ;,' l', ' m'' n',' o',' p',' q',' r& #39;,','',' u',' v',' w',& #39; x',' y',' z'];
wins = 0;
losses = 0;
guessesSoFar = []; // this is an array value
guessesLeft = 9;
// computer chooses a letter and it is assigned a variable name
var computerCurrentChoice = lettersIndex[Math.floor(Math.random() *
lettersIndex.length)];
console.log(" 1 computerCurrentChoice " + computerCurrentChoice);
//Computer picks a letter and gets stored as computerChoice
var runLoop = function () { // ELIMINATING THE FUNCTION HAD NO EFFECT ON
PROGRAM WORKABILITY
// when User presses key it launches a function to execute process
document.onkeyup = function (event) {
//when user preses letter key it is stored as var userGuess
var userGuess = event.key;
console.log("userGuess " + userGuess);
// If the user and the computer choose the same letter:
// wins adds 1,
// guessesLeft is reset to 9,
//guessesSoFar logs the letter choice into array
//alert is launched notifying user of win
if (userGuess === computerCurrentChoice) {
wins++;
guessesLeft = 9;
guessesSoFar = [];
alert("You won!!!");
// if userGuess and computerChoice are different:
// guessesLeft decreases 1,
//guessesSoFar logs the letter choice into array
}
if (userGuess != computerCurrentChoice) {
guessesLeft--;
guessesSoFar.push(userGuess);
// if guesses left reached 0:
//alert is launched notifying user of loss
// guessesLeft and guessesSoFar are reset to 10 and 0 respectively,
// losses adds 1
if (guessesLeft < 1) {
alert("You lose!");
guessesLeft = 9;
guessesSoFar = [];
losses++;
}
}
// Rewrites the html with updated values
document.getElementById('wins').innerHTML = "Wins: " + wins;
document.getElementById('losses').innerHTML = "Losses: " + losses;
document.getElementById('guessesLeft').innerHTML = "Guesses Left: " +
guessesLeft;
document.getElementById('guessesSoFar').innerHTML = "Guesses So Far: " +
guessesSoFar;
console.log(" 2 computerCurrentChoice " + computerCurrentChoice);
}
}
runLoop(); // ELIMINATING THE FUNCTION HAD NO EFFECT ON PROGRAM
WORKABILITY