结帐这个演示/游戏我正在构建http://awebdeveloper.github.io/runners/
我想知道所有球员何时完成比赛。 Game类需要知道所有玩家何时停止以及谁先到达。
我的问题是有没有办法在所有settimeout后的每个动画完成时通知回调用类
玩家等级
function Players(ele, ptimeout)
{
this.movePositions = [0, 40, 80, 120],
this.moveBy = 5
this.el = ele;
this.i = 0;
this.stop = 1;
this.timeout = ptimeout;
this.position = 0;
this.animate = function(){
/* Stop if stopped */
playerPosition = this.el.getBoundingClientRect();
if(this.stop || playerPosition.left > (racetrack.offsetWidth - 30)){
this.el.style.backgroundPosition = '120px 0px';
return ;
}
playerPosition = this.el.getBoundingClientRect();
if(this.stop || playerPosition.left > (racetrack.offsetWidth - 30)){
this.el.style.backgroundPosition = '120px 0px';
return ;
}
/* Prepare Next Move */
setTimeout(function(_this){
if(_this.i < _this.movePositions.length ){
_this.i ++;
}
else{
_this.i = 0;
}
_this.move();
_this.animate();
},this.timeout,this);
};
this.play = function(){
if(this.stop === 1){
this.stop = 0;
this.animate();
}
};
this.move = function(to,positionIndex){
this.position = to;
this.el.style.backgroundPosition = '-'+this.movePositions[positionIndex]+'px 0px';
this.el.style[getSupportedPropertyName('transform')] = 'translate('+to+'px)';
}
}
游戏类
function Game(noOfPlayers){
var track_tmpl = '<div class="track"><div id="player{{ x }}" class="runner"></div></div>';
this.noOfPlayers = noOfPlayers;
this.players = new Array();
for (var i = 0; i < this.noOfPlayers ; i++){
var timeout = 120 + getRandomInt(1, (this.noOfPlayers*2));
racetrack.appendChild(createNode(track_tmpl.replace('{{ x }}', i)));
this.players.push(new Players(document.getElementById('player' + i), timeout));
}
this.play = function(){
for (var i = 0; i < this.noOfPlayers; i++){
this.players[i].play();
}
};
}
答案 0 :(得分:0)
on Player.play
传递this
参数,从Person调用来自Game的函数。
所以你会有这样的代码
this.play = function(){
for (var i = 0; i < this.noOfPlayers; i++){
this.players[i].play(this);
}
};
然后在播放器上修改像这样的代码
this.play = function(game){
if(this.stop === 1){
this.stop = 0;
this.animate(game);
}
};
on on method animate之后调用game.playerFinished(Player)
在Game类上写一个方法
var i = 0;
this.playerFinished = function(player) {
console.log(player.name + " finished on position " + (i++));
}
其中player.name是您在玩家类上提供的名称