繁体   English   中英

如何编写循环遍历if语句的循环?

[英]How can I write a loop that cycles through my if statements?

我目前正在制作一个农业游戏,您在其中使用盆栽植物。我拥有的每个盆栽均应可单击,并应提供在其中播种的选项。 到目前为止,我想出了一种非最佳方式来实现这一目标。 我想知道是否可以使用循环以更少的代码行整齐地循环每个语句。

这是我当前的代码如下所示:

if (HUD.pots == 1) {
    // First pot 230, 502, 40, 50. Every new pot adds 50 to X
    if (mouseOver(mx, my, 230, 502, 40, 50)) {
        AudioPlayer.getSound("menu_sound").play();
        Game.gameState = STATE.Game;
        return;
    }
} else if(HUD.pots == 2) {
    if (mouseOver(mx, my, 230, 502, 40, 50)) {
        AudioPlayer.getSound("menu_sound").play();
        Game.gameState = STATE.Game;
        return;
    } else if (mouseOver(mx, my, 280, 502, 40, 50)) {
        AudioPlayer.getSound("menu_sound").play();
        Game.gameState = STATE.Game;
        return;
    }
} else if (HUD.pots == 3) {
    if (mouseOver(mx, my, 230, 502, 40, 50)) {
        AudioPlayer.getSound("menu_sound").play();
        Game.gameState = STATE.Game;
        return;
    } else if (mouseOver(mx, my, 280, 502, 40, 50)) {
        AudioPlayer.getSound("menu_sound").play();
        Game.gameState = STATE.Game;
        return;
    } else if (mouseOver(mx, my, 330, 502, 40, 50)) {
         AudioPlayer.getSound("menu_sound").play();
         Game.gameState = STATE.Game;
         return;
    }
}

当我最终要在游戏中添加更多的底池时,我将需要很多行来遍历所有底池。

对于另一种情况,我也有类似的问题:每次购买新锅时,如何使它产生x + 50 码:

// Buy Pot 
if (mouseOver(mx, my, 220, 140, 40, 20)) {
    AudioPlayer.getSound("menu_sound").play();
    if (HUD.money >= UpgradePrices.potPrice) {
        HUD.money -= UpgradePrices.potPrice;
        HUD.pots += 1;
    if (HUD.pots == 1) {
        handler.addObject(new Pot((int)230, (int)502, ID.Pot, handler));
    } else if (HUD.pots == 2) {
        handler.addObject(new Pot((int)280, (int)502, ID.Pot, handler));
    } else if (HUD.pots == 3) {
         handler.addObject(new Pot((int)330, (int)502, ID.Pot, handler));
    }

    Game.gameState = STATE.Upgrades;
    return;

看看这是否是您想要的:

for(int x=0; x<HUD.pots; x++){
    if(mouseOver(mx, my, 230+(x*50), 502, 40, 50)){
        AudioPlayer.getSound("menu_sound").play();
        Game.gameState = STATE.Game;
        return;
    }           
}

这将替换所有if语句的冗长序列。 但是,在我看来,您在这里很难编码很多东西。

对于购买锅,您可以应用相同的想法:

if (mouseOver(mx, my, 220, 140, 40, 20)){       //Assume this position is fixed
    AudioPlayer.getSound("menu_sound").play();
    if (HUD.money >= UpgradePrices.potPrice){
        HUD.money -= UpgradePrices.potPrice;
        HUD.pots += 1;
    }
    for(int x=0; x<HUD.pots; x++){             //Once again, this will replace all the ifs
        handler.addObject(new Pot(( 230+(x*50), 502, ID.Pot, handler )))
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM