luke luke - 1 month ago 9
Javascript Question

Keep track of variables within class when using method multiple times

I come from a Ruby background so having a bit of bother trying to learn some Javascript. I init a class called

Game
and insert the number of players into it. I have a method of this class called
move
which makes a move for the player. The trouble I am having is if I make multiple moves in a row that the variables are reset every time the method is run.

With the move method, I want to keep track of the current players move while also keeping track of the total dice played regardless of the player who's move it is.

Do you have any insight? Would appreciate all the help! Thanks.

function Game(players) {
_players = createPlayers(players);
_total_dice = totalDice(players);

this.move = function(id, dice, value) {
current_player = _players[id - 1];
current_player = { id: current_player.id, dice_middle: dice, value: value, dice_left: current_player.dice_left - dice }
total_dice = _total_dice - dice;
}
}


function createPlayers(amount) {
var players = [];
var player_count = new Array(amount).join().split(',').map(function(item, index){ return ++index; })

for ( var i = 0; i < player_count.length; i++) {
player = { id: i + 1, dice_middle: 0, value: 0, dice_left: 5 }
players.push(player);
}

return players;
}

function totalDice(amount) {
total = amount * 5;
return total;
}


and this is how I am init the
Game
and making moves.

var game = new Game(4);
game.move(1, 2, 3);
game.move(1, 1, 3);


Every move, re-inits the variables so in this example, total dice stays at 20, and player ones moves aren't "saved".

Answer

Functions are just functions, they do not behave like a class. Try using the ES6 class, should do what you want - example below (untested):

class Game {
   constructor(players) {
     this._players =  this.createPlayers(players);
     this._total_dice = this.totalDice(players)       
   }

   move (id, dice, value) {
     current_player = this._players[id - 1];
     current_player = { id: current_player.id, dice_middle: dice, value: value, dice_left: current_player.dice_left - dice }
     total_dice = this._total_dice - dice;
   }


   createPlayers(amount) {
     var players = [];
     var player_count = new Array(amount).join().split(',').map(function(item, index){ return ++index; })

     for ( var i = 0; i < player_count.length; i++) {
        player = { id: i + 1, dice_middle: 0, value: 0, dice_left: 5 }
        players.push(player);
     }

     return players;
  }


  totalDice(amount) {
     total = amount * 5;
     return total;
  }
}