3

我正在开发一个基于 JS 的游戏,我正在跟踪几个用户的分数。在游戏结束时,我需要宣布获胜者。可能有联系。

所以,举两个例子:

player1 = 3
player2 = 5
player3 = 4

(玩家 2 获胜)

player1 = 4
player2 = 2
player3 = 4

(玩家 1 和 3 平局)

只有 3 名玩家,我可能只是用一堆嵌套的 if/else 来比较每个值,但想知道是否有更优雅的方法来解决这个问题......尤其是在你可能有的情况下以 10 个玩家为例,if/else 比较会很快变得笨拙。

一种选择似乎是将值粘贴在数组中,然后对其进行排序,但这并没有给你变量名——只是值。然后我可以做一个多维数组,但那时事情似乎又变得一团糟。

4

3 回答 3

8

在不使用或要求这些变量是全局变量的情况下,没有简单的方法可以遍历变量名,例如player1,等,这通常是一种不好的方法。player2eval()

如果它们是全局变量,你可以使用这个技巧,但我建议我在下面使用我的第二种方法,将玩家信息存储为对象数组。这是使用全局变量的技巧(不推荐,但更直接地回答了您的问题):

// these must be global variables
var score1 = 100;
var score2= 99;
var score3= 80;

function findHighScore() {

    var highestScore = score1;
    var highestScorePlayerNum = 1;
    var tempScore;

    for var (i = 2; i <= 3; i++) {
        // this works only because the score variables are global variables which
        // can be accessed as properties off the window object
        tempScore = window["score" + i];
        if (tempScore > highestScore) {
            highestScore = tempScore;
            highestScorePlayerNum = i;
        }
    }
    return {score: highestScore, playerNum: highestScorePlayerNum};
}

更好的方法是不将每个玩家的分数保存在自己的 javascript 变量中,而是将其放入如下对象数组中:

var playerData = [
    {name: "John", highScore: 145, lastPlayed: 23089234},
    [name: "Bill", highScore: 99, lastPlayed: 59383945}
];

然后,您可以遍历玩家数据,找到最高分并获得该玩家的姓名。

function findHighScore() {
    var highScoreSoFar = 0;
    var result;
    for (var i = 0; i < playerData.length; i++) {
        if (playerData[i].highScore > highScoreSoFar) {
            result = playerDatra[i];
            highScoreSoFar = playerData[i].highScore;
        }
    }
    return result;
}

var highPlayer = findHighScore();
alert("Highest scoring player is " + highPlayer.name + " with a score of " + highPlayer.highScore);

如果要返回所有得分最高的玩家,可以返回得分最高的玩家数组:

function findHighScore() {
    var highScoreSoFar = 0;
    var result = [];
    for (var i = 0; i < playerData.length; i++) {
        if (playerData[i].highScore > highScoreSoFar) {
            // new high score so start a new array with this player in it
            result = [playerData[i]];
            highScoreSoFar = playerData[i].highScore;
        } else if (playerData[i].highScore === highScoreSoFar) {
            // more than one player with this highScore so add this one to the array
            result.push(playerData[i]);
        }
    }
    return result;
}
于 2013-04-19T00:32:05.227 回答
2
var players = []; // Array of player scores.

// Assumes that all player scores are higher than -1. You could change this.
var winnerScore = -1, winner = 0;
for (var i = 0; i < players.length; i++) {
    if (players[i] > winnerScore) {
        winner = i;
        winnerScore = players[i];
    }
}

alert("The winner was player " + winner + "!");

这应该可以解决问题:)如果你想处理领带,你可以这样做:

var players = []; // Array of player scores.

// Assumes that all player scores are higher than -1. You could change this.
var winnerScore = -1, winners = [];
for (var i = 0; i < players.length; i++) {
    if (players[i] > winnerScore) {
        winners = [i];
        winnerScore = players[i];
    } else if (players[i] == winnerScore) {
        winners.push(i);
    }
}

if (winners.length == 1) {
    alert("The winner was player " + winners[0] + "!");
} else {
    alert("The winners were players " + winners.join(", ") + "!");
}
于 2013-04-19T00:31:56.273 回答
2
var players = {
    player1: 3,
    player2: 5,
    player3: 4
};

var sorted = Object.keys(players)
                   .sort(function(keya, keyb) {
                       return players[keyb] - players[keya];
                   })
                   .forEach(function(key) {
                       console.log(key, players[key]);
                   })

演示:http: //jsfiddle.net/WUAhS/

玩家2 5

玩家 3 4

播放器1 3


或者.reduce(),如果您想要的只是高分,请使用。

var high_key = Object.keys(players)
                     .reduce(function(keya, keyb) {
                         return players[keya] > players[keyb] ? keya : keyb;
                     });
于 2013-04-19T00:37:24.060 回答