0

I have an object representing a player and let us say 2 players

//create a player object
function player(name,state,score) {
    this.name = name;
    this.state = state;
    this.score = score;
} 

 var players = [
new player('player1',true,0),
new player('player2',false,0)
];

so I want the players to make a move one after another. For that purpose I use true or false state. So when true, it counts (I count the right answers of player and display them) for player 1 and vs.

what I have for now is

$("#check").click(function(){
if(localCorrect == 2){

//counting number of correct cards and assigning it to the player
    var i=0; 
        if (players[i].state == true){
        var localscore = players[i].score;
        localscore++;
        score[i] = localscore;
//display the score
        $("span#"+players[i].name).html(score[i]);

        players[i].state = false;
        i++;
        players[i].state = true;
        //if(i=2)
        //{i=0}
        }

}else{
//some other thing
    }
});

I have a feedle with this http://jsfiddle.net/ycycghwq/

So I have 2 question:

  1. I think I'm wrong with the declaration of var i (it represents an index of a player, I have 2 of them so it should count to 1 and then go back to 0 at this point. But I want to make it not dependant on a particular number, so that it could be 4 or 10 players.

  2. I need to switch the state of the current player(i). player1 needs to be true and when switch to false. then the state of player 2 needs to be swithced from false to true. (So if I have more that 2 players I need to switch the state of the following one to true and the to false)

My brain of the beginner is boiling. Could someone please help?! Thanks in advance!

Aleksandra Chuprova
  • 493
  • 2
  • 6
  • 18

2 Answers2

0
  • Answer 1:

Declare i outside of your handler before its setup. Instead of i++; write i = (i+1) % num_of_players; and define the variable num_of_players; % is the modulo operator computing the remainder of a division. If used as outlined it repeatedly iterates from 0 to num_of_players-1. Using players.length in place of num_of_players is equivalent.

  • Answer 2:

The players' states are initialize when you create the player objects. In your given code replace players[i].state = false;, players[i].state = true; with players[i].state = !players[i].state;.

Working demo: this fiddle.

Note

  • You needn't use the equality test operator on boolean variables; if (players[i].state) { ... will suffice.

  • If you use test for equality, use the type-safe variant === instead of ==.

collapsar
  • 17,010
  • 4
  • 35
  • 61
  • Hi, thank you for your answer. I have tried it, but it doesn't work. It works once. everything happens like it should except the code reacts only the first time the button is clicked. http://jsfiddle.net/8ff4eofv/2/ I guess I need there a kid of loop, like suggested in the other answer. – Aleksandra Chuprova Feb 27 '15 at 06:42
  • Forthe sake of completeness: The content of your fiddle were incomplete and my answer contained a little bug. See the working version [here](http://jsfiddle.net/8ff4eofv/10/). Lesson learned, complete and tested code will be provided next time :-). Thanks for testing the suggestion. – collapsar Feb 27 '15 at 07:12
  • Yeah, something that you won't stop is learning :-) But that will be my turn to say thanks for working solution. One question though. Do I really need to make i and num_players global variables? And, I just need to ask - there is the other answer by @Hristo Enev which also works (above). But it is done through the loop there... so Guys, which methods is the more ...sufficient, better from the point of semantics and performance??? – Aleksandra Chuprova Feb 27 '15 at 16:26
  • The technique is the same. @HristoEnev's loop iterates through the player array once per mouse click to find the currently active player and modifies his state, passing the activity flag to the next player. That's what my code does too, however, I maintain the state in the index variable `i` and thus do not have to search the player array. In production code you wouldn't use global variables but add attributes to control the state to the `players` object. Imho, the code portion is too small consider performance in a meaningful way. Both codes do their job (shh: I like my solution better ;-)). – collapsar Feb 27 '15 at 16:36
0

I modified your code a bit. Now you can have x number of players in the array and they will switch their states just fine. I commented the most important parts so I don't think you will have problem reading the code. If you have just ask :)

JSFiddle: http://jsfiddle.net/ycycghwq/2/

var score = [0,0];
var localCorrect = 2;

$(document).ready(function(){

//create a player object
var Player = function(name, state, score) {
    this.name = name;
    this.state = state;
    this.score = score;
} 

var players = [
    new Player('player1',true,0),
    new Player('player2',false,0)
];

$("#check").click(function(){
    if(localCorrect == 2) {
        // iterate through all the players
        for(var iterator = 0; iterator < players.length; iterator++) {
            // check if there is array/object element with this key
            if (players.hasOwnProperty(iterator)) {
                var player = players[iterator];

                // check for player state
                if (player.state === true) {
                    // increment player score
                    player.score++;
                    score[iterator] = player.score;

                    $("span#" + player.name).html(score[iterator]);
                    player.state = false;

                    // check if there is next player in the array
                    // if not start from the first player
                    if (players.hasOwnProperty(iterator + 1)) {
                        var nextPlayer = players[iterator + 1];
                        nextPlayer.state = true;
                    } else {
                        var firstPlayer = players[0];
                        firstPlayer.state = true;
                    }

                    // exit the for loop
                    break;
                } else {
                    // some other thing
                }
            }
        }
    }
});
});

EDIT:

You don't create variable in players object/array. You create a variable iterator for the for..in loop. That variable represents each key of the array (in this case players). So your iterators will be 0 and 1 for the 2 iterations of the loop. You can use that also to iterate through objects and to get their property names and much more.

Documentation of for..in loop

Anyway it's my bad to use for..in loop and not a sequential for loop in this situation:

for(var iterator = 0; iterator < players.length; iterator++)

That way we don't need to parse the iterator to integer. Read more about when to use for..in loop and when sequential for loop:

Community
  • 1
  • 1
Hristo Enev
  • 2,421
  • 18
  • 29
  • Thank you very much for the awesome solution! it works perfectly well ! :-) But as I've said, I'm rather a beginner.Could you please point out exactly what and where (var iterator in players) is? Do you create a variable in players object/array as a string and then convert it to a integer? Maybe a stupid question...But I'm trying to understand. – Aleksandra Chuprova Feb 26 '15 at 19:11
  • I have edited my answer. Btw are you from Bulgaria ? :) – Hristo Enev Feb 27 '15 at 09:23
  • I really appreciate what you're doing. Thanks for the edit and for the docs. That will be some study :-) yeah, meanwhile I've read something about for in and just sequential loops... it's also a new lesson for me. So much new! I'm russian by origin, but very good integrated in the Netherlands :-) – Aleksandra Chuprova Feb 27 '15 at 16:19
  • Yeah, I just need to ask one more question: solution by @collapsar (below) is also a working solution http://jsfiddle.net/8ff4eofv/10/ that is done without the loop. Which solution is actually better from the point of view of semantics and performance in the end? – Aleksandra Chuprova Feb 27 '15 at 16:30
  • I think in that particular case @collapsar example is better, but I'm sure you you will find my answer very helpful and you will find easy solutions to your future problems once you understand the conception. :)) Cheers from Bulgaria – Hristo Enev Feb 28 '15 at 17:24