簡體   English   中英

GUI-國際象棋游戲將碎片拖放到板上“ 2D陣列”

[英]GUI - Chess game drag pieces and drop into a board “ 2D array ”

您好,我正在嘗試制作國際象棋游戲,到目前為止,我已經創建了棋子,並且可以用鼠標移動它們。

現在,我嘗試使用包含棋子的2D陣列制作棋盤,以便我在棋盤上拖動棋子時將其添加到數組中,例如圖像上

我將棋子拖到(2,3)board[2][3] = pawn

例

但是我不確定如何實現它,我想過使用像將其拖動到中間時那樣的坐標,說我的幀尺寸為800x800,板尺寸為8,所以當我將其拖動到坐標(400,400)board[4][4] = pawn ,但是然后我必須為每個單元格做它,如果有條件的話,我將得到64,是否有某種技巧可以做到?還是我的方法錯誤?

If( piece's position is between ... and ... ){
then put into board[0][1]}

If ( piece's position is between ... ) {
then put then put into board[1][1]} 

您可以在開發板上的JLabel上使用mouseListener! 首先,使用8 * 8(chess為8 * 8,對嗎?)JLabel來構建板,並將它們存儲在某個數組中。

JLabel[][] boardFields = new JLabel[8][8];

您可以將它們打包在具有GridBagLayout的JPanel中。 您可以使用GridBagContraints v gridxgridy變量輕松地將它們按所需的樣式gridy

現在,您要做的是在某個地方創建一個靜態變量,讓我們將其稱為selectedPiece 讓我們將鼠標偵聽器添加到我們所有的字段標簽中:

for(int i=0;i<8;i++){
   for(int j=0;j<8;j++){

      boardFields[i][j] = new JLabel();
      //set its background white or black here

      //each field will listen to a mouse press (means we selected this piece)
      //and a mouse release (meaning we placed the selected piece here)
      boardFields[i][j].addMouseListener(new MouseAdapter(){

           public void mousePressed(MouseEvent e){
                selectedPiece = //set piece on this field somehow
                //update the background to plain black or white
                //make the icon of the piece follow the cursor
           }

           public void mousePressed(MouseEvent e){
                //update the background to contain the selectedPiece
                //make the icon of the piece stop followin the cursor
                 selectedPiece = null //de-select the piece since we just placed it
           }
      )};
   }
}

顯然,這只是一個草圖,但是應該可以給您帶來靈感!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM