[英]Javascript Weighted Probability Array
我正在开发一个在浏览器中运行的非常基本的游戏。 准备好文档后,我创建了一些Javascript,该JavaScript显示了来自较大链接列表的随机链接(两个列表均存储在Array中)。 我的问题分为两个部分-一个简单,一个复杂:
1)有没有一种方法可以使此代码更优雅-数组中数组内的函数非常难看...
2)有没有一种方法可以将概率分配给项目,以使某些概率比其他概率更高? 目前,这只是随机的,任何“按钮”都可能像其他任何按钮一样出现。
这是我的代码:
的HTML
<body>
<h1 id="OTM_Test">Javascript Probability</h1>
<div id="stackoverflow">
<a href="nextpage.html" id="button1" class="button">Next Page 1</a>
<a href="nextpage.html" id="button2" class="button">Next Page 2</a>
<a href="nextpage.html" id="button3" class="button">Next Page 3</a>
<a href="nextpage.html" id="button4" class="button">Next Page 4</a>
<a href="nextpage.html" id="button5" class="button">Next Page 5</a>
<a href="nextpage.html" id="button6" class="button">Next Page 6</a>
</div>
</body>
CSS .button{ background:blue; color:white; display:none; margin:200px; padding:10px; display:none; border:2px solid red; }
.button{ background:blue; color:white; display:none; margin:200px; padding:10px; display:none; border:2px solid red; }
Javascript / jQuery
$(document).ready(function(){
var button1 = $("#button1");
var button2 = $("#button2");
var button3 = $("#button3");
var button4 = $("#button4");
var button5 = $("#button5");
var button6 = $("#button6");
var totalArray = [button1,button2,button3,button4,button5,button6];
function randomChoice(){
var randomNumber=Math.floor(Math.random()*6);
return randomNumber;
};
var selectedArray = [(totalArray[(randomChoice())]), (totalArray[(randomChoice())])];
function reduceArray(){
for(i=0;i<selectedArray.length;i++){
(selectedArray[i]).show();
}
};
reduceArray();
});
任何想法/想法将不胜感激。
这是我在这里的第一篇文章...请保持温柔!
这是一个更简洁的版本:
$(document).ready(function(){
var totalArray = [];
$('#stackoverflow').children().each(function(){
totalArray.push($(this)):
});
function randomChoice(){
var randomNumber=Math.floor(Math.random()*3)+Math.floor(Math.random()*3); //middle buttons have more chance of apearing
return randomNumber;
};
var selectedArray = [totalArray[(randomChoice()], totalArray[randomChoice()]];
$.each(selectedArray,function(index,object){
$(object).show();
}
});
甚至更短的代码:
function randomChoice(){
var randomNumber=Math.floor(Math.random()*3)+Math.floor(Math.random()*3); //middle buttons have more chance of apearing
return randomNumber;
};
$('#button'+ randomChoice()).show():
$('#button'+ randomChoice()).show():
为了概率,您可以设置html数据属性:
<a href="nextpage.html" id="button1" class="button" data-change="20">Next Page 1</a>
.. means 20% change of apearing
var total = 0;
$('#stackoverflow').children().each(function(){
totalArray.push($(this)):
if($(this).data('change')>Math.random()*100){
$(this).show();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.