减法逻辑的加法
Addition to Subtraction logic
这是我的代码我不知道如何将逻辑改为减法
var slices = $("#slices");
var options = $("#options");
var area = $("#area");
var selected;
var result;
//---Array of images
var pizzas = [
{image: "http://s23.postimg.org/6yojml8vb/Pizza_One.png", value: 1},
{image: "http://s13.postimg.org/5d8zxnb2b/pizzatwo.png", value: 2},
{image: "http://s12.postimg.org/xfsxldqyx/pizzathree.png", value: 3},
{image: "http://s14.postimg.org/d6tdq0865/pizzafour.png", value: 4}
];
var total = pizzas.length;
//---Make boxes dragables
options.find("div").draggable();
//---When the boxes are dropped
area.droppable({
drop: function(event, ui){
if( Number( ui.draggable.attr("data-index") ) == result ){
alert("correct");
}else{
alert("incorrect");
}
}
});
//---Insert random pizza slices
function insertPizzas(){
selected = [];
result = 0;
//---Generate aleatory pieces
var rand
while(selected.length < 2){
//---Random value
rand = Math.floor( Math.random() * total );
//---Sum result
result += pizzas[rand].value;
selected.push( rand );
}
//---Clear the slices
slices.html("");
//---Add the new slices
selected.forEach(function(number){
var img = $("<img/>");
img.attr("src", pizzas[number].image);
slices.append(img);
});
}
insertPizzas();
https://jsfiddle.net/elchininet/2u5xtkv2/
如何将逻辑从加法变为减法?
我在html页面的一部分也有这段代码,我正在开发新的变量名
以下是处理减法的jsfiddle更新:
https://jsfiddle.net/wvary/2u5xtkv2/8/
功能取自新小提琴:
//---Insert random pizza slices
function insertPizzas() {
selected = [];
result = 0;
//---Generate aleatory pieces
var rand = 0;
while (selected.length < 2) {
//---Making sure first number is greater than 0 (0 is the index so it is actually has a value of 1)
while (selected.length === 0 && rand === 0) {
rand = Math.floor(Math.random() * total);
console.log('first: ' + rand);
}
//---Making sure second number is greater than first number
while (selected.length === 1 && rand >= result) {
rand = Math.floor(Math.random() * total);
console.log('second: ' + rand);
}
//---Because of the number values, we can simply use the index difference as the values
//---Of course, we have to update our code if the values are different
if (selected.length === 0) {
result = rand;
} else {
result -= rand;
}
selected.push(rand);
}
//---Clear the slices
slices.html("");
//---Add the new slices
selected.forEach(function(number) {
var img = $("<img/>");
img.attr("src", pizzas[number].image);
slices.append(img);
});
}
需要注意的几件事:
- 我们必须在第一次迭代中循环,以确保第一个索引不是0,因为第一个数字减去第二个数字必须大于0,因为我们的选择是1到8
- 我们必须在第二次迭代中循环,以确保第二个数字小于第一个数字,原因与#1相同
- 由于我们的值都是1的差值,我们可以简单地使用index作为我们的差值
- 此外,我们必须将rand值初始化为0,第一个循环才能工作
相关文章:
- 没有找到相关文章