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

时间:2015-12-16 08:50:13

标签: java loops

我目前正在制作一个农场游戏,您可以使用花盆种植植物。我拥有的每个花盆都应该是可点击的,并且应该提供在其中种植种子的选项。到目前为止,我已经提出了一种非最佳的方法来实现它。我想知道是否可以使用循环以更少的代码行整齐地循环遍历每个语句。

这是我目前的代码:

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;

2 个答案:

答案 0 :(得分:4)

看看这是不是你想要的:

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语句的长序列。 但是,在我看来,你很难在这里编写很多东西......

答案 1 :(得分:0)

对于购买花盆,您可以使用相同的想法:

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 )))
    }
}