gpt4 book ai didi

javascript - OO Javascript Game,如何将玩家添加到游戏的玩家数组中?

转载 作者:行者123 更新时间:2023-11-28 15:47:53 26 4
gpt4 key购买 nike

这是一个非常简单的面向对象的 JavaScript 游戏的开始。我在将玩家添加到 Games Players[] 数组时遇到问题。如何做到这一点?

我删除了所有与问题无关的代码

var BobsGame = function(){
this.Players = [];
}

BobsGame.prototype.addPlayer = function(Player){
//not working
Player.Game = this;
this.Players.push(Player);
Player.setId = function(this.Players.length) {
return this.Players.length;
}
return this;
}

var Player = function(name){
this.Game = null;
this.score = 0;
this.name = name;
this.id = null;
// return alert('Player ' + this.name + ' has been created');
}

var myGame = new BobsGame();

var Player1 = new Player("Tom");
var Player2 = new Player("Bob");

myGame.addPlayer(Player1);

最佳答案

我认为你正在尝试:

var BobsGame = function () {
this.Players = [];
};

BobsGame.prototype.addPlayer = function (Player) {
this.Players.push(Player);
Player.id = this.Players.length;
return this;
};

var Player = function (name) {
this.score = 0;
this.name = name;
this.id = null;
// return alert('Player ' + this.name + ' has been created');
};

var myGame = new BobsGame();

var Player1 = new Player("Tom");
var Player2 = new Player("Bob");

myGame.addPlayer(Player1);

错误出现在以下代码中:

Player.setId = function(this.Players.length) {
return this.Players.length;
}

在这里,您尝试创建一个名为 setId 的函数,但您无法定义 this.Players.length作为一个论点。因此,假设您尝试将玩家的 id 设置为玩家数组的长度,您可以像这样简单地分配它:

Player.id = this.Players.length;

顺便说一句,我建议您不要调用 addPlayer 的参数“Player ”,因为这将隐藏已定义的函数 Player 。您可能想将其重命名为“player ”。

关于javascript - OO Javascript Game,如何将玩家添加到游戏的玩家数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21648014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com