2017-11-27 59 views
-2

* 먼저 내 영어가 좋지 않아 나를 이해하려고하십시오. 나는 슬라이드 퍼즐 게임을 만들려고하지만 슬라이드 이벤트에 대한 블록 및 방법을 클릭 슬라이드하는 방법에 대해 이해하지 못했다. (나는 MouseLister을 의미) 지금 내가 도움을 단지 GUI슬라이드 퍼즐에서 코드를 수행하는 방법. 자바에

public PGWindow() { 
    JFrame frame = new JFrame("SlidePuzzle"); 
    JPanel Board = new JPanel(); 
    Board.setLayout(new GridLayout(3, 3)); 
    Font fn = new Font("Tahoma", Font.BOLD, 60); 
    int Num = 1; 

    for (int row = 0; row < 3; row++) { 
     for (int col = 0; col < 3; col++) { 
      if (Num == 9) { 
       break; 
      } 
      else { 
       Board.add(new JButton(String.valueOf(+Num))).setFont(fn); 
      } 
      Num++; 
     } 
    } 

    frame.add(Board); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(600, 600); 
    frame.setLocation(600, 90); 
    frame.setVisible(true); 
} 

감사 있습니다.

답변

0

저는 Java GUI에 익숙하지 않지만 이러한 힌트가 당신이 원하는 것을 성취하는데 도움이되기를 바랍니다.

누군가가 블록 8을 클릭한다고 상상해보십시오. 클릭 이벤트가 트리거되고 블록을 효과적으로 슬라이드하는 메소드를 호출해야합니다.

블록을 옮길 수 있는지 확인하고 게임 상태를 보유하는 행렬을 정의한 일부 메서드 slideBlock(int blockId)을 만들어야합니다.

주문을 시작해야하며 사용자가 퍼즐을 재정렬 할 수있는 방법을 찾기 위해 정확한 퍼즐을 섞는 방법을 정의해야합니다. 약간의 의사 코드를 보자.

//The matrix initial state: 
int[][] grid = new int[gridLength][gridLength]; 
int piece = 1; 

//Fill the grid with the puzzle ordered: 
for(0<=row<gridLength) { 
     for(0<=col<gridLength) { 
      if(row != gridLength - 1 && col != gridLength - 1) { //Leave last block empty 
       grid[row][col] = piece 
       piece++ 
      } 
     } 
} 

public void shuffle() { 
     //Some shuffle that makes sense 
} 

public void slideBlock(int blockId) { 
     //Get the indexes where the block is, e.g. getPositions() and hold them on some vars, e.g. row, col 
     boolean moved = false; 

     if(row - 1 > 0 && grid[row - 1][col] == 0){ // Move block up 
      grid[row - 1][col] = blockId 
      moved = true; 
     } 
     else if(row + 1 < gridLength - 1 && grid[row + 1][col] == 0) { // Move block down 
      grid[row + 1][col] = blockId 
      moved = true; 
     } 
     else if(col - 1 > 0 && grid[row][col - 1] == 0) { // Move block left 
      grid[row][col - 1] = blockId 
      moved = true; 
     } 
     else if(col + 1 < gridLength - 1 && grid[row][col + 1] == 0) { // Move block right 
      grid[row][col + 1] = blockId 
      moved = true; 
     } 

     if moved 
      grid[row][col] = 0 // Delete the piece from old position 
} 

희망이있다.

+0

감사합니다. (0 <행

+0

변수'row'가'0'에서'gridLength - 1', 즉'for (int row = 0; row LuisFerrolho