2014-03-13 36 views
-1

我正在開發一個大學的國際象棋遊戲,我遇到了以下問題: 如果玩家點擊棋盤的某個區域,我可以使用x,y座標檢測他選擇哪個棋子,並將這些座標到包含32個元素(僅僅是對矢量Pieces [32]的引用)和32個空指針的矩陣(tabPieces)8x8的索引中。問題是我不知道如何將棋子移動到另一個地方,只有當棋手第二次點擊棋盤的不同x,y座標時,我如何檢測到第二次點擊? PS:我的意思是第二次點擊而不是雙擊鼠標。如何檢測鼠標在不同的時間和地點被點擊兩次?

@Override 
public void mouseClicked(MouseEvent e) { 
    coordenadaReal(e.getX(), e.getY()); 

    try { 
     // get NullPointerException if the player click in one of the 32 null positions(do not have any chess piece in these coordinates) 
     if ((x > 0 && x < 512) && (y > 0 && y < 512)) { // if not clicked on the edge board 
      int colorClicked = tabPecas[indLineTab][indColumnTab].getColor(); 

      tabPieces[indLineTab][indColumnTab].showPossiblePaths(x, y, colorClicked); 

      // I do not know how to detect this second click to do this part. 
      // if the player click a second time in a valid place for that piece then walk to a new position 
      tabPieces[indLineTab][indColumnTab].walk(x, y); 
      tabPieces[indLineTab][indColumnTab] = null; // this position is empty and i do not lose the piece because tabPieces just store the reference and not the object 

     } 
    } catch (Exception exc) { 
    } 
} 

回答

1

你需要保持某種標誌的指示狀態的比賽是...

private boolean hasPiece = false; 
//... 

public void mouseClicked(MouseEvent e){ 
    if (hasPiece) { 
     // Move the piece that the user previously selected... 
     hasPiece = false; 
    } else { 
     // Select the piece that the user clicked on... 
     hasPiece = true; // but only when the user clicked on a valid piece ;) 
    } 
} 
+0

這是一個非常簡單的解決方案。我在發佈這個問題後就想到了類似的東西,我想知道如果這個解決方案會導致一些問題,比如說玩家從皇后變成了塔,比我意識到這不是一個問題,因爲這不應該是一個有效的運動。謝謝 –

+1

@RoniCésardeCastro你可以放一些更多的邏輯,所以如果他們點擊另一個有自己的片斷,你只需切換狀態,但這取決於你想如何處理它... – MadProgrammer

0

您可以通過檢查位置,以及當你點擊鼠標第二次做到這一點。所以如果再次點擊鼠標,請確保點擊發生在相同的座標上。 希望這會幫助你