一旦满足一个案例条件,如何在switch语句中更改案例?

时间:2016-09-16 19:32:31

标签: javascript jquery html

我正在试图弄清楚如何在Javascript / jQuery中切换案例。我正在创建一个骰子游戏,玩家需要掷骰子直到完成“阶段”。一旦完成“阶段”,他们将进入下一个“阶段”,之前的任何“阶段”都不会干扰当前的“阶段”。将有几个不同的“阶段”,它们从“阶段1”开始,然后一直工作到“阶段2”,依此类推,直到最后阶段。有什么方法可以解决“阶段”吗?我在这里尝试一个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);

3 个答案:

答案 0 :(得分:0)

在提出问题之前,我想提一下你的if / else语句:

if(roll1 === 1) {
    die1Array.push(1);
}
else if(roll1 === 2) {
    die1Array.push(2);
}

如果您要将roll1的值放入die1Array而不管值是什么,为什么每次都先检查它?只需做一个die1Array.push(roll1);并称之为一天。

我认为你甚至根本不需要切换声明。您希望通过switch语句实现什么目标?

代码的逻辑基本上是这样的:

var main = function() {
    // onclick stuff
    lvls = 1
    switch(lvls){}
}

这将立即进入此switch语句,其硬值为1,紧接着它,因此总是遇到第一种情况。

这个逻辑似乎更适合调用各种函数。也许phaseTwo(){...}的函数,但switch语句主要用于检查特定点的项目状态,而不是跟踪状态随时间的变化。

答案 1 :(得分:0)

die#功能中,您可以在没有 if else 部分的情况下推送值。

var die1 = function () {
    var roll1 = Math.floor(Math.random() * 6) + 1;
    die1Array.push(roll1);
}

或者更一般:

var die = function(dieArray){         dieArray.push(Math.floor(Math.random()* 6)+ 1);    }

使用:

模具(die1Array);   死亡(die2Array);   死亡(die3Array);   ...

您当前的 swithc 的问题是您在案例中绑定了一个事件处理函数。

如果您希望该事件处理程序仅在特定状态下工作,则应设置状态变量以保存当前状态并在处理函数中检查此变量。

var main = function () {
    var diceState = 1;

    $("#submit").click(function() {
            if (diceState === 1) {
                // do something
            }
        });

    switch(lvls) {
    case 1:
          diceState = 1;
          break;

    case 2: 
         diceState = 2;
         break;
    }

您遇到的另一个问题是您在主函数中将 lvls 的值设置为1,因此您将只有1个案例, lvls 的其他更改即使你再次打电话给 main ,也没有任何效果。

如果你多次调用 main ,那么你就会遇到连续绑定事件 onsubmit 的问题,所以每次提交表单时,函数处理程序多次被召唤。

您应该将开关语句移动到另一个函数中,将状态变量作为参数传递,并在每次要更改状态时调用。

所以这里有一个例子:

// Should be in same scope of the function
// or an attribute of an object to be passed by reference.
var diceState;

var changeState = function (state) {
    switch(state) {
    case 1:
        diceState = 1;
        break;
    ....
    default:
        throw new Error("State " + state + " not supported");
    }
}

使用默认案例来处理意外值是一种很好的做法。

这里有关于如何更改主要功能的建议:

var main = function() {

    var lvls;

    $("#roll").on("click", die1);
    $("#roll").on("click", die2);
    $("#roll").on("click", die3);
    $("#roll").on("click", die4);
    $("#roll").on("click", die5);
    $("#roll").on("click", die6);

    var changeState = function (state) {
        switch(state) {
        case 1:
            alert("Phase 1");
            lvls = state;
            break;

        case 2:
            alert("Phase 2");
            //Phase 2's code
            lvls = state;
            break;

        //Additional cases/Phases would go here.
        default:
        };
    }

    // bind the event handler
    $("#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");
                changeState(2);

                // you could not return the vaue here!
                // return lvls; 
            }
            else {
                alert("Phase 1: Straight of 3.  Not Complete.  Try again.");
            };
        });

     changeState(1);

};

答案 2 :(得分:0)

以下是一些有用的ES6代码。

它定义了数组中每个阶段的名称和验证函数。 <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="http://www.youwebsite.com/home/">Home</a></li> <li><a href="http://www.youwebsite.com/blog/">Blog</a></li> <li><a href="http://www.youwebsite.com/contact/">Contact me</a></li> </ul> </li> 函数执行5次骰子(可以是任意数字)的随机生成几次,所以给出一些动画,然后回调,提供每个骰子的值。

然后使用全局roll变量来查找并执行正确的验证功能。如果通过,lvl会递增:

lvl
const dieFaces = [null,'&#9856;','&#9857;','&#9858;','&#9859;','&#9860;','&#9861;'];
const DICE_COUNT = 5;
var lvl = 0;
var phases = [
    {
        descr: 'Phase 1: Pair',
        test: function (counts) {
            return counts.some( count => count > 1 );
        }
    },
    {
        descr: 'Phase 2: Three of a Kind',
        test: function (counts) {
            return counts.some( count => count > 2 );
        }
    },
    {
        descr: 'Phase 3: Full House',
        test: function (counts) {
            return counts.some( count => count > 2 ) &&
                   counts.filter( count => count > 1 ).length > 1;
        }
    },
    {
        descr: 'Phase 4: Small Straight',
        test: function (counts) {
            return counts.map( count => count>0 ).join('').indexOf('1111') > -1;
        }
    },
    {
        descr: 'Phase 5: Large Straight',
        test: function (counts) {
            return counts.map( count => count>0 ).join('').indexOf('11111') > -1;
        }
    },
    {
        descr: 'Phase 6: Four of a Kind',
        test: function (counts) {
            return counts.some( count => count > 3 );
        }
    }
];

function roll(callback, rolling = 20) {
    let faces = [];
    let dice = [];
    for (let i = 0; i < DICE_COUNT; i++) {
        let die = Math.floor(Math.random() * 6) + 1;
        dice.push(die);
        faces.push(dieFaces[die]);
    }
    $('#dice').html(faces.join(' '));
    if (!rolling) return callback(dice);
    setTimeout(roll.bind(null, callback, rolling-1), 50);
}

$("#roll").on("click", function () {
    $('#result').text("");
    roll(function (dice) {
        var acc = dice.map( die => 0 );
        dice.forEach( die => ++acc[die] );
        if (phases[lvl].test(acc)) { 
            $('#result').text("Completed " + phases[lvl].descr);
            lvl++;
            $('#phase').text(phases[lvl].descr);
        } else {
            $('#result').text("Try again");
        }
    });
});

$('#phase').text(phases[0].descr);
#dice { font-size: 40px }

相关问题