Javascript精神游戏

时间:2017-11-02 14:14:14

标签: javascript

我正在创建一个猜谜游戏,并试图得到一个条件,不允许我的用户选择相同的答案两次。我想在某种程度上说如果userGuess不等于我创建的空跨度(用户猜测)中的项目,那么没有任何反应。我是javascript的新手,只需要一些方向!

<!DOCTYPE html>
<html lang="en-us">
<head>
	<meta charset="utf-8">
	<title>Psychic Game</title>
</head>
<body>

	<div id="game">
		<h1> The Psychic Game </h1>
		<p>Guess what letter I'm thinking of!</p>
		<p>Wins:</p>
		<p>Losses:</p>
		<p>Guesses Left:</p>
		<p>Your Guesses so far:</p>
	</div>

	<script type="text/javascript">
		
		 var computerChoices = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",];

		 var wins = 0;
		 var losses = 0;
		 var numGuesses = 9;
		 var guessChoices = [];

		 document.onkeyup = function(event) {

		 	var userGuess = event.key;

		 	var computerGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)];

		 	var options = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",];
		 	

			if (options.indexOf(userGuess) > -1) {

				if (userGuess === computerGuess) {
					wins++;
					numGuesses = 9;
					guessChoices = [];
				}

				if (userGuess != computerGuess) {
					numGuesses --;
					guessChoices.push(userGuess);
				}

				if (numGuesses === 0) {

				numGuesses = 9;
				losses ++;
				guessChoices = [];

				
			}

			var html = 
			"<h1> The Psychic Game </h1>" +
			"<p>Guess what letter I'm thinking of!</p>" +
			"<p>Wins: " + wins + "</p>" +
			"<p>Losses: " + losses + "</p>" +
			"<p>Guesses Left: " + numGuesses + "</p>" +
			"<p>Your Guesses so far: " + guessChoices.join(", ") + "</p>";

			document.querySelector("#game").innerHTML = html;

			
			}
		};

	</script>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

如果您到目前为止创建了用户答案的​​数组

var userAnswers = [];

并且做到这一点,无论何时你回答,它都会检查所有以前的答案,看它是否与之匹配。

var isDuplicate = false;
for (var i = 0; i < userAnswers.length; i++) { //for every previous answer
    if (currentAnswer == userAnswers[i]) { //check if the current answer is a previous one
        isDuplicate = true;
        break; //exit loop
    }
}
if (!isDuplicate) { //different than previous
    userAnswers[userAnswers.length] = currentAnswer;
    //do other code here
}

答案 1 :(得分:0)

我会使用array.includes方法检查guessChoices是否包含用户当前的猜测,看起来像这样:

if (options.indexOf(userGuess) > -1) {
    if (userGuess === computerGuess) {
        wins++;
        numGuesses = 9;
        guessChoices = [];
    }
    else {
        if (guessChoices.includes(userGuess)) {
            // Code for duplicate guess
        }
        else {
            numGuesses--;
            guessChoices.push(userGuess);
        }
    }

    if (numGuesses === 0) {
        numGuesses = 9;
        losses++;
        guessChoices = [];
    }
}   

但是,您正在重置计算机对每个按键的猜测,因此可能会产生一些意想不到的结果。