Pergunta

I'm trying to create a simple game that has a function that selects a random div(out of a selection)and then sets a random countdown using an interval and when the countdown hits 0 the class of that div will change. Then i have it so when you click on something assigned with that class it will change back to the original class.

At the moment when i'm running my code the divs seem to be changing after the countdown but won't change when i click them. But my main problem is that the main function that changes the random divs is only running once.

The divs ("box") start as .wait

My code:

var react = function(){
    var box = parseInt(Math.random()*64);

    while($("box"+box).hasClass("now")) {
        box = parseInt(Math.random()*64);
    }

    var timer = parseInt((Math.random()*10)+2);

    var countdown=setInterval(function(){
        timer-=1
        $("#box"+box).text(parseFloat(timer.toFixed(0)));

        if(timer<=0){
            clearInterval(countdown)
            $("#box"+box).text("");
            $("#box"+box).text("");
            $("#box"+box).removeClass("wait");
            $("#box"+box).addClass("now");
        }
    },1000)
}

$(document).ready(function(){
    //paint\\
    //$(".wait").click(function() {
    //$(this).toggleClass("now")
    //})
    //paint\\

    setInterval(react(),1000);

    $(".now").click(function(){
        $(this).removeClass("now");
        $(this).addClass("wait");
    })
})
Foi útil?

Solução 2

"But my main problem is that the main function that changes the random divs is only running once."

i'm assuming that you're referring to the following line.

setInterval(react(), 1000);

modify it as follows:

setInterval(react, 1000);

update:

assuming you've a fixed number of div, you can assign a common handler for all of them at page load like

$(document).ready(function(){
  $('your-common-div-selector').click(function(){
    if($(this).hasClass("now")&& !$(this).hasClass("wait")) {
      this.removeClass("now");
      this.addClass("wait");
  });
});

Outras dicas

The issue is how you're binding your click event. You'll want to delegate that event, rather than use click().

When setInterval runs, it adds a class, 'new' to an element. However, since no elements had that class name (when calling click() in $doc.ready), no handler is triggered.

First, a fiddle demonstrating this works: http://jsfiddle.net/yvvMp/

Here's an example using your code + delegating the events:

var react = function(){
    var box = parseInt(Math.random()*64);

    while($("#box"+box).hasClass("now")) {
        box = parseInt(Math.random()*64);
    }

    var timer = parseInt((Math.random()*10)+2);

    var countdown=setInterval(function(){
        var $el = $('#box' + box);

        timer-=1
        $el.text(parseFloat(timer.toFixed(0)));

        if(timer<=0){
            clearInterval(countdown);

            $el.text("")
               .removeClass("wait")
               .addClass("now");
        }
    },1000);
}

$(document).ready(function(){
    $parent = $('.parent-to-now-elements') // $('body') works, but not as efficient
    setInterval(react, 1000);

    $parent.on('click', '.now', function(){
        $(this).removeClass("now");
        $(this).addClass("wait");
    })
})

Tilwin's answer will work, but you run into the chance that the same element could have multiple event handlers bound. Depending on how long the game runs, and how often a user gets the same DIV element randomly selected, your DOM could look something like:

<div class='wait wait wait wait wait wait wait wait wait'></div>

Worse, each time jQuery calls the click handler, you're forcing the browser to touch the DOM (depending on the game, this could be bad!)

Here's an example: http://jsfiddle.net/pjMcv/ (When a block turns green, click it. Then wait for it to turn red again and click...)

(Tilwin has edited his answer, removing .click out of setInterval. His edited answer is better, but it still has a downside - it requires n number of event bindings. Works for simple games, but if your game has 1000 squares, you'll have 1000 event handlers)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top