2

I can't figure this out. What's happening is that when I click a div in playerMove() it should make the var clickedId that id. It works if I click one div and then another div, but if I click the same div twice the variable doubles and adds one. For example:

1st click = 3 2nd click = 4 This works fine

1st click = 3 2nd click = 3 This creates something like var clickedId = 3 3 3 3

Here's the fiddle jsfiddle.net/61cyw2s8

$(document).ready(function() {
    //Global Arrays
    var player = [];
    var comp = [];

    //function for RandomInt 1-4  
    function randomInt() {
        return Math.floor(Math.random() * (4 - 1 + 1) + 1);
    }

    //hover function
    function hover(value) {
        $("#" + value).addClass("hover");
        setTimeout(function() {
            $("#" + value).removeClass("hover");
        }, 500);
    };

    //Comp Move
    var hoverCount = 0

    function addCompMove() {
        comp.push(randomInt());
        compHover();

    }

    function compHover() {
        setTimeout(function() {
            console.log(hoverCount);
            hover(comp[hoverCount]);
            hoverCount++;
            if (hoverCount < comp.length) {
                compHover();
            }
        }, 1000)
        playerMove();
    };

    //Player Move 
    function playerMove() {
        $(".playbox").on("click", function() {
            var clickedId = parseInt(this.id);
            console.log(clickedId);
            player.push(clickedId);
            hover(clickedId);
            correctMove();
        })
    }
    //Testing
    function arrayEqual(arr1, arr2) {
        if (arr1.length !== arr2.length) {
            return false;
        }
        for (var i = arr1.length; i > -1; i--) {
            if (arr1[i] !== arr2[i])
                return false;
        }
        return true;
    };

    function correctMove() {
        if (arrayEqual(comp, player)) {
            hoverCount = 0;
            player.length = 0;
            addCompMove();
        } else {
            playerMove();
        }
    };
    //Start
    $("#start").bind("click", function() {
        addCompMove();
    });

});
Elliott McNary
  • 1,149
  • 3
  • 11
  • 20

3 Answers3

1

check the array to not duplicate $.inArray

//Player Move 
function playerMove(){
  $(".playbox").on("click", function(){
    var clickedId = parseInt(this.id);
    console.log(clickedId);
    if ($.inArray(clickedId, player) == -1){
       player.push(clickedId);
    }
    hover(clickedId);
    correctMove();
  }) 
}
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
  • I don't think it's an issue with the array according to the console. It's the variable doubling when it's clicked twice in a row. Just tried this and it doesn't work. Still same thing occuring – Elliott McNary Dec 10 '15 at 10:07
  • @ElliottMcNary this is what I talking about.. http://jsfiddle.net/mohamedyousef1980/61cyw2s8/2/ .. the array stop pushing .. and I comment //correctMove(); cause after some clicks this function hang my PC I think you create a huge random number .. Please tell me exactly what you trying to do – Mohamed-Yousef Dec 10 '15 at 11:15
  • I'm trying to recreate the Simon game. I think I have narrowed it down. I think it has to do with the hoverComp function invoking the callback in the if(). This is causing it to call playerMove multiple times. Any ideas how to call playerMove, but only once the hoverComp is done? – Elliott McNary Dec 10 '15 at 11:19
  • Figured it out. Had to move the playerMove(); to the start button click function. The issue was that it kept calling the playerMove() function when it shouldn't have so it was doubling it's actions. Thanks so much for you help! – Elliott McNary Dec 10 '15 at 11:28
  • @ElliottMcNary no need to thank me .. I need to thank you cause you solved it .. Good Luck :) +1 to your answer – Mohamed-Yousef Dec 10 '15 at 11:31
1

Turns out the callbacks to playerMove() were causing it to double the values. I moved it into the '.start' button function and it's working great.

$(document).ready(function(){
  //Global Arrays
 var player = [];
  var comp = [];
var hoverCount = 0;
  var clickedId = 0;
//function for RandomInt 1-4  
function randomInt()
{
    return Math.floor(Math.random()*(4-1+1)+1);
}

//hover function
function hover(value){
  $("#" + value).addClass("hover");
  setTimeout(function(){
    $("#" + value).removeClass("hover");
  }, 500);
};

//Comp Move

function addCompMove(){
 comp.push(randomInt());
  compHover();

}

 function compHover()
  {setTimeout(function (){ 
  hover(comp[hoverCount]);
  hoverCount++;
  if (hoverCount < comp.length){
    compHover();
    };    
  }, 1000);
  };

//Player Move 
function playerMove() {
    $(".playbox").on("click", function() {
     clickedId = parseInt(this.id);
        console.log(clickedId);
        player.push(clickedId);
        console.log(player)
        hover(clickedId);
        correctMove();
    });
}
  //Testing
function arrayEqual(arr1, arr2){
  if (arr1.length !== arr2.length){
    return false;
  }
  for (var i = arr1.length; i > -1; i--){
    if(arr1[i] !== arr2[i])
    return false;
  }
  return true;
}; 
function correctMove(){
  if(arrayEqual(comp, player)) {
     hoverCount = 0;
    player.length = 0;
     addCompMove();
     }
};
//Start
$("#start").bind("click", function(){
  addCompMove();
  playerMove();
});

});
halfer
  • 19,824
  • 17
  • 99
  • 186
Elliott McNary
  • 1,149
  • 3
  • 11
  • 20
0

Is this Simon Says? That's cool. That's an exercise in recursive timeIntervaled (or maybe setTimeout?) Hell :P

Disregard the previous answer, I gave your problem a little more thought and wrote 2 functions to replace 2 of your functions.

compArrays(arr1, arr2) to replace arrayEqual(arr1, arr2)

Both functions give the same result, I just don't like the reverse loop in arrayEqual it gives me the heebee jeebees. 0_o It returns true if the arrays are identical and in the same exact order. Recommended usage:

var match = compArrays(player, comp);

function correctMove() {
    if (match) {
        hoverCount = 0;
        player.length = 0;
        addCompMove();
    } else {
        playerMove();
    }
}; 

randomInt(min, max) to replace randomInt()

The new randomInt takes min and max which defines the range, the parameters are EXCLUSIVE so the range is covered better. In your case usage would be as follows:

randomInt(0, 5);

That will return a randomly generated integer within the range of 1 to 4.

The functions and tests are in this PLUNKER

/* compArrays(arr1, arr2) 
Compares 2 arrays, returns true if: elements are identical and in the same order
*/
function compArrays(arr1, arr2) {
  if (arr1.length !== arr2.length) return false;
  for (var i = 0, len = arr1.length; i < len; i++) {
    if (arr1[i] !== arr2[i]) {
      return false;
    }
  }
  return true;
}

//http://stackoverflow.com/a/22395370/2813224

/* randdomInt(min, max)
Returns a randomly genrated integer from a range determined by given parameters:
min and max are EXCLUDED (ex. range of 1 to 10, min=0 and max=11)
*/
function randomInt(min, max) {
    result = (Math.floor(Math.random() * max + (min + 1)) % max) || max;
    return result;
}

//http://stackoverflow.com/a/12523228/2813224

function test1() {
var arr1 = [3, 0, 1, 2];
var arr2 = [3, 0, 1, 2];
var arr3 = [3, 1, 0, 2];
var arr4 = [2, 1, null, 3];
var match = compArrays(arr1, arr2);
var order = compArrays(arr2, arr3);
var nul0 = compArrays(arr1, arr4);
console.log('arr1 and arr2 match: ' + match);
console.log('arr2 and arr3 match: ' + order);
console.log('arr1 and arr4 match: ' + nul0);
}

function test2(len) {
  var tmp = [];
  for (var i = 0; i < len; i++) {
    var ran = randomInt(0, 5);
    tmp.push(ran);
    console.log('Random 1 to 4: ' + ran);
  }
  console.log('Random array: ' + tmp.toString());
}


test1();
test2(8);

Assuming you are actually iterating playerMove(), and it's results are the same on each iteration, then you most likely need to increment the return value, so try incrementing clickedId.

function playerMove() { $(".playbox").on("click", function() { var clickedId = parseInt(this.id) =+ 1; //Try incrementing clickedId console.log(clickedId); player.push(clickedId); hover(clickedId); correctMove(); }) }
zer00ne
  • 41,936
  • 6
  • 41
  • 68