-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が10ではなく36のように追加されます。正しく行われる場合もあれば、それほど煩わしくない場合もあります。

4

1 に答える 1

8

UI コンポーネントの再描画が必要になるたびに呼び出されるメソッド、paint(...) でクラスレベルの変数を更新しています。私はそれが迷惑であることを驚かない。

クリック アクションを処理するロジックをペイント メソッドから分割し、ペイント メソッドを使用してコンポーネントの現在の状態だけをレンダリングする必要があります。

編集:あなたのコメントに加えて、アプリケーションの構造を知らなくても、次のようなものが必要になると思います:

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 に答える