当多次使用方法时,跟踪类中的变量

Keep track of variables within class when using method multiple times

本文关键字:变量 跟踪 使用方法      更新时间:2023-09-26

我有Ruby背景,所以尝试学习一些Javascript有点麻烦。我初始化一个名为Game的类,并将玩家数量插入其中。我有一个这个类的方法叫做move,它使玩家移动。我遇到的麻烦是,如果我在一行中进行多次移动,每次方法运行时变量都会重置。

对于move方法,我想要跟踪当前玩家的移动,同时也要跟踪所掷骰子的总数,而不管玩家是谁在移动。

你有什么见解吗?感谢所有的帮助!谢谢。

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;
}

这就是我如何在Game和移动。

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

每次移动,重新启动变量,所以在这个例子中,骰子总数保持在20,并且玩家的移动不会被"保存"。

函数只是函数,它们的行为不像类。尝试使用ES6类,应该可以做你想做的——下面的例子(未经测试):

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;
  }
}

您已经编写了inside move函数

   this.move = function(id, dice, value) {
         total_dice = _total_dice - dice;
      }

如果我假设正确,total_dice有一个错字,它应该是_total_dice。缺少"_"