-3
//Pylons
int xCoord[];
int yCoord[];
int numSquare;
boolean firstPaint;

public void init() {
    //Images Call
    pylon = getImage(getDocumentBase(), "image/pylon.png");
    numClicks = 0;

    //pylons
    xCoord = new int[100];
    yCoord = new int[100];
    numSquare = 0;
}

public void paint(Graphics g) {
    if (numClicks == 0) {
        drawUI(g);
        //probeDraw(g,2);
    }

    if (numSquare == 1) {
        for (int k = 0; k < numSquare; k++) {
            g.drawImage(pylon, xCoord[k], yCoord[k], this);
        }
        Minerals -= 100;
        popMax += 9;
    }
}

public boolean mouseDown(Event e, int x, int y) {
    if (numClicks == 10) {//Title screen        
        numClicks++;
        repaint();
    }

    if (numSquare == 0) {
        xCoord[numSquare] = x;
        yCoord[numSquare] = y;
        numSquare++;
        repaint();
    }
    return true;
}

当我这样做而不是仅仅减去 100 时,它会将其设置为 -300 并且它将 popMax 添加到 36 而不是 10。有时它会正确,有时它不会真的很烦人

4

1 回答 1

8

您正在更新paint(...) 中的类级变量,该方法在每次ui 组件需要重新绘制时调用。我并不惊讶它很烦人。

您需要将处理单击操作的逻辑从绘制方法中分离出来 - 并使用绘制方法仅呈现组件的当前状态。

编辑:根据您的评论,在不知道您的应用程序结构的情况下,我想您需要这样的东西:

private void handlePylonPlacement()
{
    if(decrementMinerals(-100))
        addPopMax(9);
} 

private boolean decrementMinerals(int amount)
{ 
    if(MaxMinerals - amount >= 0) // prevent situation where you go into negative minerals
    {
         MaxMinerals -= amount;
         return true;
    }
    else
         return false;
}

private void addPopMax(int amount)
{
    if(popMax + amount <= MAX_POPULATION) // restrict addition to pop-max to a sane upper bound
         popMax += amount;
}

public boolean mouseDown(Event e, int x, int y) {
    if (numClicks == 10) {//Title screen        
        numClicks++;
        repaint();
    }

    if (numSquare == 0) {
        xCoord[numSquare] = x;
        yCoord[numSquare] = y;
        numSquare++;
        handlePylonPlacement(); // call your new handler
        repaint();
    }
    return true;
} 
于 2012-05-15T13:35:47.877 回答