我来自Ruby背景,所以有点麻烦尝试学习一些Javascript。我创建了一个名为Game
的类,并将玩家数量插入其中。我有一个名为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,并且玩家的移动不会“保存”。
答案 0 :(得分:1)
函数只是函数,它们不像一个类。尝试使用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;
}
}
答案 1 :(得分:0)
你已写入内部移动功能
this.move = function(id, dice, value) {
total_dice = _total_dice - dice;
}
如果我假设正确,则有一个拼写为total_dice,它应该是_total_dice。缺少“_”