我正在制作一个西蒙游戏,其中两个玩家对抗AI和彼此。为了简化事情,从长远来看,我会重写大量代码,以便将所有内容保存在单个播放器中#34;阵列。但是,我很难想到如何能够跟踪游戏中的某些事情,例如谁将其转变,或者哪些对象数据进入。< / p>
// player1和player2都是= $(&#34;#name&#34;)。val()其中#name是输入并验证的输入框
player[player.length] = {
name: player1,
points: 0,
gamesWon: 0,
gamesLost: 0,
gamesTied: 0,
sequence: null,
correct: false
};
player[player.length] = {
name: player2,
points: 0,
gamesWon: 0,
gamesLost: 0,
gamesTied: 0,
sequence: null,
correct: false
};
这将是一个不断增长的阵列,其中存储了无限数量的玩家。例如,稍后在我的代码中,如果我想要修改第二个玩家的积分,我是否必须制作一个:
for(i=0; i < player.length; i++){if (player[i].name === $("#name").val()) {
//在这里做点什么;}}
是否有更简单的方法来查找玩家并修改阵列位置的值?或找到我需要的其他东西?
答案 0 :(得分:0)
您可以通过数字和名称为玩家编制索引。
var players = []
function joinGame(playerName) {
var playerNumber = players.length;
players[playerName] = {
name: playerName,
number: playerNumber
};
players[playerNumber] = players[playerName];
}
joinGame('player0');
joinGame('player1');
console.log('-- by player number --');
console.log(players[0]);
console.log(players[1]);
console.log('-- by player name --');
console.log(players['player0'])
console.log(players['player1']);
console.log('-- forEach on the array --');
players.forEach(function(p) {
console.log(p);
});
答案 1 :(得分:0)
您可以使用jQuery.grep( )
搜索数组。因为您有一个对象数组,grep( )
函数允许您匹配特定条件,包括对象的属性。此函数返回您在数组中查找的对象,而不会影响原始数组。用法示例:
var players = [];
player[0] = {
name: player1,
points: 0,
gamesWon: 0,
gamesLost: 0,
gamesTied: 0,
sequence: null,
correct: false
};
player[1] = {
name: player2,
points: 0,
gamesWon: 0,
gamesLost: 0,
gamesTied: 0,
sequence: null,
correct: false
};
$player2 = $.grep( player, function( p ) { p.name === "player2"; } ); //Returns the player2 object
grep( )
功能的文档可在http://api.jquery.com/jquery.grep/找到,this stackoverflow answer也可以参考。