JQuery随机数猜测游戏:循环困境

时间:2015-01-10 06:16:42

标签: javascript jquery while-loop numbers

我正在尝试制作一个简单的数字猜谜游戏:生成1到9999999999之间的随机数并打印到控制台。我希望用户在表单中输入他们的猜测 - 并保持循环猜测,直到猜测与随机数匹配。

这是我的HTML:

<!DOCTYPE html>
<html lang="en">
   <head>
       <meta charset="UTF-8">
       <title>Random Number Guess</title>
       
 
   </head>
   
<body>

   <!--text display/button -->

    <p>Try and "guess" the random number! Click "Generate new random number" to start"</p>
	<div id="out1"></div>
	
	<form id="promptUser">
		Your guess:
		<input type="text" id="inUserGuess">
		<input type="submit" value="Submit">
	</form>
	<br>
	<button id="btn1">Generate new random number</button>
	<div id="in1"></div>

  
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  
  <script>/*SEE SCRIPT BEOW */</script>
 </body>
 
</html>
 

这里是javascript / jquery:

$(document).ready(function() {

			/*initialize random number*/
			var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
			console.log(randNum);


				var win = false;
				while (win = false) {

					$('#promptUser').on('submit', function(e){
						e.preventDefault;

					var userGuess = $('#inUserGuess').val();
					console.log("User guess:" + userGuess);
				});

				/*yes: "congrats! start again"*/
				if (userGuess == randNum){

					console.log("User guess is correct");
					alert("You got it! Try another round.");
					win = true;

				} 
				/*no: "not quite. guess again."*/ 
				else {

					console.log("user guess is incorrect");
					alert("Not quite. Guess again.");
					win = false;
				}
			
			}

为了让用户猜测直到他们做对了,我将猜测输入放在while循环中并使用if和else语句来确定他们的猜测是否与随机数匹配。

似乎代码在if / else语句之前的某个地方搞砸了 - 控制台日志永远不会显示出来。相反,按下提交时会生成一个新的随机数。

我知道收集输入的语法 - 在我尝试给用户无限猜测之前if语句运行正常(尽管在每次“play”之后自动生成一个新的随机数,无论正确/不正确的猜测)

我觉得这很愚蠢 - 但我已经花了好几个小时摆弄它。

[[EDIT]]我现在让提交按钮事件处理程序执行两项操作:将用户输入存储到userGuess并检查它是否与randNum匹配,但仍然陷入无限循环:

   <script> 



		

			/*initialize random number*/
			var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
			console.log(randNum);

			var userGuess = "";

			do {

			$(document).ready(function() {

				$('#promptUser').on('submit', function(e){
						e.preventDefault;

					userGuess = $('#inUserGuess').val();
					console.log("User guess:" + userGuess);
					
				  
					if(userGuess == randNum){
			        console.log("user guess is correct");
			        alert("That's right! Play again.");
				
			       }  
				    else{
					console.log("user guess is incorrect");
					alert("Not quite. Guess again.");
					
				  }

				});
		});
		}
			while (userGuess != randNum);
			
			
			
				

				/*generate new random number each on button click */
			$('#btn1').on('click', function(){

				var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
				console.log(randNum); /*(return random number to console for cheating)*/

			});
	
	
				
       </script>

0 个答案:

没有答案