我想弄清楚如何在Javascript/jQuery中的案例之間切換。我正在創建一個骰子游戲,玩家需要擲骰子直到完成「階段」。一旦完成「階段」,他們將進入下一個「階段」,任何先前的「階段」都不會干擾當前的「階段」。將會有幾個不同的「階段」,他們從「階段1」開始,到「階段2」,等到最後階段。有什麼辦法可以解決「階段」?我在這裏嘗試了一個switch語句,但沒有成功。如果switch語句不能完成這項工作,會有什麼結果?一旦滿足一個案例條件,如何在switch語句中更改案例?
//Start of Dice Code
var die1Array = [];
var die2Array = [];
var die3Array = [];
var die1 = function() {
var roll1 = Math.floor(Math.random() * 6) + 1;
if(roll1 === 1) {
die1Array.push(1);
}
else if(roll1 === 2) {
die1Array.push(2);
}
else if(roll1 === 3) {
die1Array.push(3);
}
else if(roll1 === 4) {
die1Array.push(4);
}
else if(roll1 === 5) {
die1Array.push(5);
}
else if(roll1 === 6) {
die1Array.push(6);
}
};
var die2 = function() {
var roll2 = Math.floor(Math.random() * 6) + 1;
if(roll2 === 1) {
die2Array.push(1);
}
else if(roll2 === 2) {
die2Array.push(2);
}
else if(roll2 === 3) {
die2Array.push(3);
}
else if(roll2 === 4) {
die2Array.push(4);
}
else if(roll2 === 5) {
die2Array.push(5);
}
else if(roll2 === 6) {
die2Array.push(6);
}
};
var die3 = function() {
var roll3 = Math.floor(Math.random() * 6) + 1;
if(roll3 === 1) {
die3Array.push(1);
}
else if(roll3 === 2) {
die3Array.push(2);
}
else if(roll3 === 3) {
die3Array.push(3);
}
else if(roll3 === 4) {
die3Array.push(4);
}
else if(roll3 === 5) {
die3Array.push(5);
}
else if(roll3 === 6) {
die3Array.push(6);
}
};
//End of Dice Code
var main = function() {
$("#roll").on("click", die1);
$("#roll").on("click", die2);
$("#roll").on("click", die3);
$("#roll").on("click", die4);
$("#roll").on("click", die5);
$("#roll").on("click", die6);
//Where I want to switch between cases.
//Once Phase 1's condition (the if statement) is met, I want to switch to Phase 2.
var lvls = 1;
switch(lvls) {
case 1:
alert("Phase 1");
$("#submit").click(function() {
if((die1Array.slice(-1)=="1"||die2Array.slice(-1)=="1"||die3Array.slice(-1)=="1")&&(die1Array.slice(-1)=="2"||die2Array.slice(-1)=="2"||die3Array.slice(-1)=="2")&&(die1Array.slice(-1)=="3"||die2Array.slice(-1)=="3"||die3Array.slice(-1)=="3")) {
alert("Completed Phase 1: Straight of 3");
lvls = 2;
return lvls;
}
else {
alert("Phase 1: Straight of 3. Not Complete. Try again.");
};
});
break;
case 2:
alert("Phase 2");
//Phase 2's code
break;
//Additional cases/Phases would go here.
default:
};
};
$(document).ready(main);
對於初學者你爲什麼要檢查一噸擲骰子值的if/else語句,而不是僅僅增加'die1Array.push(ROLL1) '? – leigero
我也有一些骰子的圖片,如果條件得到滿足將顯示。例如:if(roll1 === 1){$(「#die-1」)。show);} – Hunter