0

I'm looking to create a simple jquery game. It starts like this, the user enters a number in a text field.

<form>
    <input type="text" id="MyNumber" value="" />
    <button id="getit">Play</button>
</form>
<div id="randomnumber"></div>

After the click the play button, a series of numbers will appear in the div id randomnumber. The objective is to click on the randomly rotating numbers in the div id randomnumber when they see the number they intered in the my number text field. If they click their number, they win.

The jquery script I have requires a button be pushed to generate the number, (I don't want a button pushed each time a new number should be generated.) The script also doesn't identify the number that was clicked, or send it to my checknumber.php page so I can store the number entered and the number picked in a database. Any help?

this is the jquery script I have.

function IsNumeric(n){
    return !isNaN(n);
} 

$(function(){
    $("#getit").click(function() {
        var numLow = $("#lownumber").val();
        var numHigh = $("#highnumber").val();

        var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
        var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);

        if (IsNumeric(numLow)
            && IsNumeric(numHigh)
            && (parseFloat(numLow) <=  parseFloat(numHigh)) 
            && (numLow != '') 
            && (numHigh != '')) 
        {
            $("#randomnumber").text(numRand);
        } else {
            $("#randomnumber").text("Careful now...");
        }

        return false;
    });

    $("input[type=text]").each(function(){
        $(this).data("first-click", true);
    });

    $("input[type=text]").focus(function(){
        if ($(this).data("first-click")) {
            $(this).val("");
            $(this).data("first-click", false);
            $(this).css("color", "black");
        }
    });
});
3
  • Why do you use php and db, if all number checking could be done with JS only? Commented Nov 15, 2010 at 5:49
  • To keep score, each time the user misses and when they hit. Commented Nov 15, 2010 at 5:51
  • So what prevents me to open up Firebug and mess up with the number checking routine so to win at the first click? ;) This type of checking should always be done server-side. Commented Nov 15, 2010 at 6:35

4 Answers 4

2

The "Play" button is good to start the ball rolling (I'm not certain if you were thinking of removing it entirely). To generate numbers periodically, use setInterval.

$(function(){
    var initialPeriod=500; // 0.5s
    var generateNumIval;
    function generateNum() {
        var numLow = $("#lownumber").val();
        var numHigh = $("#highnumber").val();

        var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
        var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);

        if (IsNumeric(numLow)
            && IsNumeric(numHigh)
            && (parseFloat(numLow) <=  parseFloat(numHigh)) 
            && (numLow != '') 
            && (numHigh != '')) 
        {
            $("#randomnumber").text(numRand);
        } else {
            $("#randomnumber").text("Careful now...");
        }
    }
    function run(period) {
        clearInterval(generateNumIval);
        generateNumIval = setInterval(generateNum, period);
    }

    $("#getit").click(function() {
        run(initialPeriod);
        return false;
    });
    ...

You can change the period (such as to increase the difficulty when the user clicks the correct number, or decreasing the difficulty when the user makes too many sequential mistakes) by calling run with a new period. If you want to change the period after generating each number, use setTimeout rather than setInterval.

To check a click on a number, register a click handler on #randomnumber that compares its val() to #MyNumber's val(). From there, take appropriate action as to whether it's a hit or miss. As Dan says, doing this for every click will create quite a bit of network traffic. Though only a small amount of data may be transmitted each time, the number of connections can cause a significant impact. Instead, have a "Stop" button and send the data if the user clicks it, or use an unload handler (one does not exclude the other).

Sign up to request clarification or add additional context in comments.

1 Comment

I really like your idea of incorporating difficult levels, I'm looking for ways to add that to WolfRevoKcats code. I couldn't get your's to work.
1

Your server will crash and burn if you have more than a couple people playing this game. People can identify and click very fast (multiple times per second), but unless they live next to your server, you can't receive and respond to HTTP requests that fast, nor can your server handle hundreds or more per second from the multiple users.

Write the game in JavaScript and when they're done, send the totals (# of wrong clicks and # of right clicks, or whatever) to your server to save. Do your best to obfuscate how they're sent so that it's not trivial to make up scores.

Comments

1

There's a couple of things to look out for here. There's no reason why the random numbers can't be generated from the number the player has entered himself, or even better, a number generated by the game itself.

The way which you've done the placeholder text, using data and two event handlers is also somewhat messy. At a minimum you should be using .one to attach a one-time event handler for this, but it would be much better if you use the HTML5 placeholder attribute with a Javascript fallback.

Other than that, you're still missing significant amount of game logic in there. I won't advice you to work on this game for too long though - it's great as an exercise in working with JavaScript and jQuery, but otherwise not very worthwhile.

Oh, and just for fun, I also built my own version of this.

var hitCount = 0,
    missCount = 0;

function IsNumeric(n) {
    return !isNaN(n);
}

$("#getit").click(function() {
    var li = [],
        intervals = 0,
        n = parseInt($('#MyNumber').val());

    if (IsNumeric(n)) {
        setInterval(function() {
            li[intervals++ % li.length].text(Math.random() > .1 ? Math.floor(Math.random() * (10 + n) + (n / 2)) : n).attr('class', '');
        }, 500);
    }

    $('#randomnumber').empty();

    for (var i = 0; i < 5; i++) {
        li.push($('<li />').click(function() {
            var $this = $(this);

            if (!$this.hasClass('clicked')) {
                if (parseInt($this.text(), 10) === n) {
                    $this.addClass('correct');
                    $('#hitcount').text(++hitCount);
                } else {
                    $this.addClass('wrong');
                    $('#misscount').text(++missCount);
                }
            }

            $this.addClass('clicked');
        }).appendTo('#randomnumber'));
    }

    return false;
});

Crude yes, but it sort of works. Have a look at it here: http://jsfiddle.net/DHPQT/

3 Comments

This looks really really good. I actually prefer the way you have it set up. You this is actually a game on my site that gamers can play and win money. So as soon as they hit, it's sent to a database and the money they won is collected. If they miss we debit the $1 from their account and $0.60 goes back into the pot. So each time a member misses the money pot goes up. But soon as they hit the money is credited to their account and the prize is reset back to $5. I have to be able to submit this to a database.
Man, that's a strangely compelling game for a couple of minutes =)
Yi here's a problem bro, members are just keeping the cursor on one box and ignoring the rest. I there a way to make it so you can't click the same box as you clicked last time?
0

For fun..

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var mainLoop;
$(function(){
  $("#getit").click(function() {
    if ($(this).attr('class') == 'start') {
      $(this).attr('class','play');
      $(this).html('STOP THE MADNESS!');
      mainLoop = window.setInterval(function() {
        var output = '';
        for (var i = 0; i < 10; i++) {
          var numLow = $("#lownumber").val();
          var numHigh = $("#highnumber").val();  
          var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
          var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
          output += '<div>'+numRand+'</div>';
        }
        $('#randomnumbers').html(output);
      },250);
    } else {
      window.clearInterval(mainLoop);
      var sweetWin = false;
      $('#randomnumbers').children().each(function() {
        var v = $(this).html();
        if (v == $('#MyNumber').val()) {
          alert('WIN!');
          sweetWin = true;
          $.post('127.0.0.1',{outcome:'win'});
        }
      });
      if (!sweetWin) {
        alert('FAIL!');
        $.post('127.0.0.1',{outcome:'loss'});
      }
      $(this).attr('class','start');
      $(this).html('Play');
    }
  });
});
</script>
</head>
<body>
Low: <input type="text" id="lownumber" value="0" />
High: <input type="text" id="highnumber" value="100" />
<input type="text" id="MyNumber" value="50" />
<button id="getit" class="start">Play</button>
<div id="randomnumbers"></div>
</body>
</html>

4 Comments

THANK YOU, Absolute Genius. I change the height of the div so only 1 number shows at a time. Now I'm going to full around with it and see If I can add the score in the database.
I spoke too soon, I see as long as the stop when their number is amongst the visible numbers they win. It's actually a bit more difficult because you have to pay attention to more than one number.
If you only want to show one number you can change the for loop to 1 instead of 10. =]
Thanks wolf, I'm using both your script and the one provided by,Yi.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.