开发者

Logic for Gold, Silver, Bronze

I'm building a game in javascript and have my results generated.

var score = array("5", "5", "1");开发者_运维百科

So player 1 has a score of 5, player 2 a score of 5 and player 3 a score of 1.

I want to display my results as 3 levels - Gold, Silver and Bronze, however if the top two results are the same I want them both to be gold, leaving the lowest score silver.

What is the best way to work this out using javascript?

Ideally my results array for this particular set of scores would look like this:

var results = array("gold", "gold", "silver");

Thanks.


Here's some code doing it:

var scores = [5, 8, 1];
scores.sort(function(a, b) {
    return (a > b) ? 1 : ((a < b) ? -1 : 0);
}).reverse();
var medals = {};
var medalsUsed = 0;
var availableMedals = ['Gold', 'Silver', 'Bronze'];
for(var i = 0; i < scores.length; i++) {
    var score = scores[i];
    var medal;
    if(medals[score]) { // already have a medal for this score value? use it
        medal = medals[score];
    }
    else { // use next available medal
        if(i >= 3) return; // but not if we've already given out 3 medals
        medal = availableMedals.shift();
        medals[score] = medal;
    }

    alert('medal for ' + i + ': ' + medal);
}

Demo: http://jsfiddle.net/ASdb8/1/


I would first sort the array then compare values (1 with 2 and 2 with 3). To sort an array of numbers you need to pass the sort function another function as an argument.

var medals = ['Gold', 'Silver', 'Bronze']; 

score = score.sort(compare);

//Return descending order
function compare(a,b){
    return b-a;
}

results[0] = medals.shift();
//I'm assuming you only want top 3  scores    
for(var i = 1; i < 3; i++){
    if(score[i] == score[i-1]){
        results[i] = results[i-1];
    }else{
        results[i] = medals.shift();
    }
}

This code sorts the scores, and if any of them are equal sets the medal to be the same as the one before it.

Proof of concept: http://jsfiddle.net/Fttmj/1/


First loop through the array and determine the highest and the next two highest scores.

Then loop through your player scores and assign "Gold" to any score that matches the highest score, "Silver" to any score that matches the second highest, and "Bronze" to any score that matches the third highest score.


Another solution is using Javascript's max() function, then comparing the gold/silver and the bronze/silver scores. if gold and silver equal, change silver to gold and bronze to silver, and if the silver and bronze are equal change the bronze to silver.


yet another method

var results = ['Gold', 'Silver', 'Bronze'];
var arr = [5, 5, 5];
arr.sort().reverse();
var currentScore = arr[0];
var idx = 0;
for(var i=0; i< arr.length; i++){
    if(arr[i]!= currentScore){
        idx++;
        currentScore = arr[i];
    }
    alert(arr[i]+ ' has ' + results[idx] + ' medal');
}

update: fiddle here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜