如何在回合中为当前球员分配积分

我已经用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);
评论
  • 牵绊情愫
    牵绊情愫 回复

    改用数组:

    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);

    Above, scores[0] will correspond to the number of points the first player has, scores[1] will correspond to the number of points the second player has, etc.