首页 > 解决方案 > 防止在jquery中重复值

问题描述

制作游戏并试图让每个水晶从 Math.floor(Math.random()) 中提取一个随机数。但我们的目标是让每个水晶都有不同的数字。我尝试做出 if 语句并说一个晶体不能等于另一个晶体,但似乎对这些方法并不满意。我需要让所有的水晶都有自己的功能吗?

    $(document).ready(function(){
        //Varriable for the number you have to guess
        var targetNumber = Math.floor(Math.random() * 101) +19;
    
      //Varriable that edits the DOM for the number we have to guess
      $(".guess_this_number").text(targetNumber);
    
      //Our number that starts at zero
      var counter = 0;
    
      //"Your Number" is chaning the DOM of to equal whatever is added
      $(".userTotal").text(counter);
    
      //Wins that starts at zero 
      var wins = 0;
      //Update DOM with wins
      $("#wins").text(wins);
    
      //losseses that starts at zero 
      var losses = 0;
      //Update DOM with losses
      $("#losses").text(losses);
    
      //The computer generated number is determined by a math random
      var targetNumber = Math.floor(Math.random() * 101) +19;
      $('.guess_this_number').text(targetNumber);
    
    
          // Object array of all the crystals. Maps a random number to each crystal
          var numbers = {
            "crystal_1": Math.floor(Math.random() * 11) +1,
            "crystal_2": Math.floor(Math.random() * 11) +1,
            "crystal_3": Math.floor(Math.random() * 11) +1,
            "crystal_4": Math.floor(Math.random() * 11) +1,
          };
          console.log(numbers)
          
          //For each 
          // key is the crystal and the value is the math.floor 
          $.each(numbers, function(key, value){
           $('.'+key).click(function(){
    
            //Counter will increase from the value of each number
            counter += value;
    
            //Prevents same number appearing twice...maybe??? 
            // if ((numbers["crystal_1"]) === (numbers["crystal_2"]) || 
            //     (numbers["crystal_1"]) === (numbers["crystal_3"]) ||
            //     (numbers["crystal_1"]) === (numbers["crystal_4"]) ||
            //     (numbers["crystal_2"]) === (numbers["crystal_3"]) ||
            //     (numbers["crystal_2"]) === (numbers["crystal_4"]) ||
            //     (numbers["crystal_3"]) === (numbers["crystal_4"])) {
            // }; nope no luck

            // or...? 
            if ((numbers["crystal_1"]) === (numbers["crystal_2"])) {
              (numbers["crystal_2"]) = Math.floor(Math.random() * 11) +1;
              (numbers["crystal_1"]) != (numbers["crystal_2"]);
            }; //no luck here either


    
            //Counter class is updated with new number, 
            //if go over the goal number lose, add loss, and reset
            $('.userTotal').html(counter);
            if(counter > targetNumber){
             $('#wlMessage').text("You Lose :(" );
               losses ++;
               $('#losses').text(losses);
               counter = 0;
               $(".userTotal").text(counter);
               $(".guess_this_number").text(Math.floor(Math.random() * 101) +19);
             }
    
              //Counter class is updated with new number, 
              //if user number equals goal numer its a win, add win, and reset
             if(counter === targetNumber){
               $('#wlMessage').text("You Won!!!");
               wins ++;
               $('#wins').text(wins);
               counter = 0;
               $(".userTotal").text(counter);
               $(".guess_this_number").text(Math.floor(Math.random() * 101) +19);
             }
    
           });
    
         });
    
        });
<!DOCTYPE HTML> 
<html>
<head>
	<meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
	
	<title>Crystal Game</title>

    <link rel="stylesheet" type="text/css" href="assets/css/reset.css">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B"
        crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
   	
   	<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>



</head>

<body>
	<!-- Container --> 
	<div class="container">
		
		<!-- Title --> 
		<div class="jumbotron">
			<h1 class="text-center">Crystal Game</h1>
			<div class="text-center">
				
				<!-- Instructions --> 
				<div class ="row">
					<div class="col-12">
						<h5>Instructions</h5>
						<p> lorem ipsum some instructions</p>
					</div>
				</div>

				<!-- The Random Computer Number --> 
				<div class ="row">
					<div class="col-12">
						<div class="col-12">Match the number</div>
						<div class ="guess_this_number"></div>
					</div>
				</div>

				<!-- Crystals --> 
				<div class ="row">
				  	<div class ="col-3 crystal_1"><img src="assets/images/crystal-01.svg"></div>
				  	<div class ="col-3 crystal_2"><img src="assets/images/crystal-02.svg"></div>
				  	<div class ="col-3 crystal_3"><img src="assets/images/crystal-03.svg"></div>
				  	<div class ="col-3 crystal_4"><img src="assets/images/crystal-04.svg"></div>
				</div>

				<!-- User number --> 
				<div class ="row">
					<div class="col-12">
						<div class="col-12">Your number</div>
						<div class ="userTotal"></div>
					</div>
				</div>

				<!-- Score --> 
				<div class ="row">
					<div class="col-12">
						<hr>
<!-- 						<div class="col-12">Score</div>
 -->						<div id="wlMessage"></div>
						<div class="row">
							<div class="col-6">
								<div><h6>Wins:</h6></div>
								<div id ="wins"></div>
							</div>
							<div class="col-6">
								<div><h6>Losses:</h6></div>
								<div id ="losses"></div>
							</div>
						</div>
					</div>
				</div>


	</div>

<script src="assets/javascript/game.js"></script>

</body>

标签: javascriptjquery

解决方案


在我的评论中,我问您是否考虑过在发布使用之前使用数组来保存数字清单;我给你写了一个简单的例子,希望能帮助或引导你朝着正确的方向前进。

下面的示例为通过单击按钮生成的数字创建一个库存数组,每次单击都会将数字添加到数组中,并且在执行某个功能之前,该数字会根据数组进行验证,以显示它是否之前已生成。

本质上,这段代码几乎是在生成唯一数字时识别它们。我已尽力对每个步骤进行评论以使其易于理解;

请看下面的代码:

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" />
      <!--<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
      <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic|Roboto+Mono:400,500|Material+Icons" />-->

      <title>Ilan's Test</title>
   </head>
   <body>

<div class="container">
    <div class="row">
        <div class='col-sm-12' style="margin-top:10px;">
            <div class="form-group">
                <a class="btn btn-primary" id="clickme" style="color:#FFFFFF;">Generate Number</a>
            </div>
            <div id="results">
            </div>
        </div>
    </div>
</div>

      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
      <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>-->

<script type="text/javascript">
    // Declare our global variables
    var numcheck = new Array(); // this array will hold all generated numbers
    var newnum; // this is our new number placeholder
    var exists; // this is our boolean indicator

    // On button click we run this function
    $('#clickme').click(function(){
            // Assign a new random number to our variable
            newnum = Math.floor(Math.random() * 11) + 1;
            // Itirate through our numcheck array and check if the number exists         
            $.each(numcheck, function(i, item) {

                if (item == newnum){
                    // If the number exists, set our indicator to true, exit this loop
                    exists = true;
                    return false;
                } else {
                    // If the number does not exist, set our indicator to true
                    exists = false;
                }
            });

            // Check our indicator what happened when we went through the array, the reason I use indicator is because if I have additional code I need this value in I can use it later
            if (exists == true){
                // If the number exists, indicate in my results log the number has been used
                $('#results').append('<span class="text-danger">' + newnum + ' has already been used.</span><br>');
            } else {
                // If the number does not exist in our array, indicate in the results it's a fresh number and do any custom coding needed in the below clause
                $('#results').append('<span class="text-success">New number generated: ' + newnum + '</span><br>');
            }

            // Add the number to the array regardless if true or false so we can analzye its length in the future if needed, the array is our number inventory which tells us when a number has been previously used
            numcheck.push(newnum);

    });

</script>

   </body>
</html>

推荐阅读