javascript – JS:如何创建一个不会两次选择相同项目的随机选择器?

我正在为游戏制作一个随机的英雄选择器,这个工具会随机为玩家选择英雄.我想添加一个功能,它为整个3人团队挑选英雄,但我不知道怎么做,以便同一个英雄不会被选中多次.以下是我为玩家挑选随机英雄的代码示例.先感谢您!!!!

<script language="JavaScript">

function pickhero(){
var imagenumber = 16 ;
var randomnumber = Math.random() ;
var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
images = new Array
images[1] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/ringo.png"
images[2] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/krul.png"
images[3] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/ardan.png"
images[4] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/saw.png"
images[5] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/petal.png"
images[6] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/adagio.png"
images[7] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/catherine.png"
images[8] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/koshka.png"
images[9] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/skaarf.png"
images[10] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/joule.png"
images[11] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/glaive.png"
images[12] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/taka.png"
images[13] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/celeste.png"
images[14] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/vox.png"
images[15] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/fortress.png"
images[16] = "http://www.vaingloryfire.com/images/wikibase/icon/heroes/rona.png"
var image = images[rand1]
document.team1hero1.src = image
}
</script>
最佳答案
首先,我会在pickhero()范围之外有一个所有英雄的数组.然后,我会有第二个数组指向原始数组,并在选择英雄时丢失元素.

这是一个简单的例子.

var heroes = ["link1", "link2", "link3", "link4"];
var heroesAvailable = [];
for (var i=0; i<heroes.length; i++) {
    heroesAvailable.push(i);  // [0, 1, 2, 3]
}

var heroesChosen = [];
for (var i=0; i<3; i++) {  // choose 3 heroes
    // the amount of heroes not chosen yet
    var imageNumber = heroesAvailable.length;
    var randHero = Math.floor(Math.random()*imageNumber);

    heroesChosen.push(heroes[heroesAvailable[randHero]]);

    // remove that hero from the available array
    heroesAvailable.splice(randHero, 1);
}

转载注明原文:javascript – JS:如何创建一个不会两次选择相同项目的随机选择器? - 代码日志