【问题标题】:randomize player color listing in javascript在javascript中随机化播放器颜色列表
【发布时间】:2018-11-06 06:19:47
【问题描述】:

我在http://verlager.com/super-dev.php 有一个国际象棋配对页面。问题是我需要随机化玩家的颜色,因为我只是按评分降序列出玩家。评分较高的玩家总是得到白色的棋子。不好。

我想我应该选择前两名球员,随机分配一个数字。如果随机数 > 0.5,则第一个玩家有白色,否则第二个玩家有白色。把它们列出来。然后让接下来的两名球员做同样的事情。有什么建议?

<script>

    // input data

    var toSort = "attaya, james j|blazak, stephen a|larrategui, martin|lionti, michael p|mackenzie, randolph|sassone, richard a|saxby, quinton tyl|trowbridge, james|".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>

【问题讨论】:

    标签: jquery random


    【解决方案1】:

    使用 CSS3

    JS

    sorted.forEach((n, x) => {
      let a = n.split(','),
          r;
    
      if (nameRatingMap[n]) {
        r = nameRatingMap[n];
        $('#I' + x).val(a[0] + '; ' + r);
      }
    });
    

    CSS

    input:nth-of-type(odd) {
      background: blue;
      color: #fff;
    }
    
    input:nth-of-type(even) {
      background: red;
      color: #fff;
    }
    

    演示:https://codepen.io/anon/pen/oyXWZO

    使用{n} % 2 === 0

    JS

    sorted.forEach((n, x) => {
      let a = n.split(','),
          r, c;
    
      if (nameRatingMap[n]) {
        r = nameRatingMap[n];
        c = (x % 2 === 0) ? 'red' : 'blue';
        $('#I' + x).val(a[0] + '; ' + r)
          .css({
            background: c,
            color: '#fff'
          });
      }
    });
    

    演示:https://codepen.io/anon/pen/bKdRzQ

    【讨论】:

      猜你喜欢
      • 2023-01-23
      • 2013-09-16
      • 1970-01-01
      • 2011-01-27
      • 2014-04-02
      • 1970-01-01
      相关资源
      最近更新 更多