I have a chess pairing page at http://verlager.com/super-dev.php. The problem is that I need to randomize the player's colors because I am just listing the players in descending order by rating. The higher rated player always gets the white pieces. Not good.
I think I should take the first two players, and randomize a number. If the random number is > 0.5, then the first player has white, else the second player has white. List them out. Then take the next two players and do the same. Any suggestions?
<script>
// input data
var toSort = "<?php echo $GLOBALS['$players']; ?>".split("|");
// SOLUTION:
// create a map.
var nameRatingMap = {};
members.forEach(function(element) {
nameRatingMap[element.Name] = element.Rating;
});
// use map for sorting
var sorted = toSort.sort(function(a, b) {
var ratingA = nameRatingMap[a] || 0;
var ratingB = nameRatingMap[b] || 0;
return ratingB - ratingA;
})
for (let i = 0; i < sorted.length; i++) {
$temp = sorted[i - 1];
//if (i % 2 !== 0) {random = Math.random();}
//if (random > 0.5;) {player_1 = sorted[i - 1]; player_2 = sorted[i];}
if ($temp && $temp.length > 0) {
var $full = $temp.split(","); var $nick = $full[0];
$name = $nick.substr( 0, 16);
$("#I" + i).val($name + ", " + $full[1].substr(0, 1) + ". " + members.find(x => x.Name === $temp).Rating);
}
}
}
</script>
from randomize player color listing in javascript
No comments:
Post a Comment