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

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

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

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;

解决方法:

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

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 )))
    }
}
上一篇:PHP-我想获得一个ID的所有父ID上的数组


下一篇:java-JOptionPane.showInputDialog循环(使用do while循环)