我已经用JS完成了一个游戏,该游戏可以很好地与2个玩家配合使用,但是我想添加让用户最多增加5个玩家的功能,因此我该如何检查谁轮到玩家来正确分配点数对他们来说,玩家数量是否由用户定义?
我的代码现在已经被两个团队硬编码了:
//team 1
let team1Points = 0;
//team 2
let team2Points = 0;
let whoPlayed = 0;
//assign points to a Team
function assignPoints(points) {
//check who's turn is it
switch (whoPlayed) {
case 0:
team1Points += points;
whoPlayed++;
break;
case 1:
team2Points += points;
whoPlayed--;
break;
}
}
assignPoints(2);
assignPoints(3);
console.log(team1Points);
console.log(team2Points);
答案 0 :(得分:1)
改为使用数组:
const NUM_PLAYERS = 5;
// Make an array filled with 0s, with a length of NUM_PLAYERS:
const scores = Array.from({ length: NUM_PLAYERS }, () => 0);
let activePlayerIndex = 0;
//assign points to a Team
function assignPoints(points) {
scores[activePlayerIndex] += points;
activePlayerIndex = (activePlayerIndex + 1) % NUM_PLAYERS;
}
assignPoints(2);
assignPoints(3);
assignPoints(66);
assignPoints(0);
assignPoints(1);
assignPoints(5);
console.log(scores);
以上,scores[0]
对应于第一个玩家的得分,scores[1]
对应于第二个玩家的得分,等等。