2012-10-26 108 views
1

我做了一个8益智游戏。我发现我的争夺方法有一些问题,但我不知道如何解决它。 有没有人可以帮助我的代码?这是争夺方法的代码。我的代码问题是,我点击加扰按钮后,数字将只有两个数字图片,然后再次点击加扰,它只在9个按钮中显示一个数字。8益智游戏争夺法

public void scramble() 
{ 
    for(int i = 0; i <SHUFFLE_NUM; i++) 
    { 
     int x1 = rand.nextInt(BOARD_SIZE); 
     int x2 = rand.nextInt(BOARD_SIZE); 
     int y1 = rand.nextInt(BOARD_SIZE); 
     int y2 = rand.nextInt(BOARD_SIZE); 

     Piece temp = board[x1][y1]; 
     board [x1][y1] = board[x2][y2]; 
     board[x1][y2] = temp; 
    } 
} 

更新

在这里,我找到另一个错误,当我点击复位键,当我试图将我的数字按钮,此举一步是错误的。在这里,我附上我的招法和复位方法

public boolean move(int _x, int _y) 
    { 

    boolean valid = false; 

    if(_x == currentCol-1 && _y == currentRow) // on the left of empty one 
     valid = true; 

    else if(_x == currentCol+1&&_y == currentRow) //on the right of empty one 
     valid = true; 

    else if(_x == currentCol&&_y == currentRow-1) // on the top of empty one 
     valid = true; 

    else if(_x == currentCol &&_y == currentRow +1) // on the bottom of empty one 
     valid = true; 

    if(valid) 
    { 
     Piece temp; 
     temp = board[_x][_y]; 
     board[_x][_y] = board[currentCol][currentRow]; 
     board[currentCol][currentRow] = temp; 

     currentCol = _x; 
     currentRow = _y; 
    } 

    return valid; 

} 

这里是复位方法

public void reset() 
    { 

    for(int i =0; i<BOARD_SIZE; i++) 
     for(int j =0; j<BOARD_SIZE; j++) 
     { 
      int value = i*BOARD_SIZE+j+1 ; 
      String filePath; 
      if(value!= BOARD_SIZE*BOARD_SIZE) 
       filePath = "Piece" + value +".jpg"; //what is this mean? 
      else 
       filePath = "blank piece.jpg"; 
      board[i][j]= new Piece(new ImageIcon(filePath),i, j, value); 

     } 

} 

举动是正确的工作,如果我没有不要点击复位键..

+2

”号码只有两个号码图片“是什么意思? –

+0

一旦你解决了这个问题(复制粘贴错误),考虑到你的炒盘可能无法解决。请参阅http://en.wikipedia.org/wiki/Fifteen_puzzle#Solvability下的“奇偶排列” – paddy

+0

关于您的更新:您是否尝试过自己进行调试? SO不是提供免费调试服务的社区。你甚至不会提供有关“错误”是什么意思的有用信息。 –

回答

3
board[x1][y2] = temp; 

这不应该是

board[x2][y2] = temp; 

更新

你打电话给你reset()方式后,您currentColcurrentRow变量将是错误的;你需要更新它们以指向新的空白部分。退出方法之前补充一点:

currentCol = BOARD_SIZE - 1; 
currentRow = BOARD_SIZE - 1; 
+0

+1击败我:D ... – MadProgrammer

+0

谢谢!你介意看我的更新,我发现我的代码 – JavaLeave

2

你交换代码是有点不对...

Piece temp = board[x1][y1]; 
board [x1][y1] = board[x2][y2]; 
board[x1][y2] = temp; // You're mapping the wrong x position here 

它应该阅读

Piece temp = board[x1][y1]; 
board [x1][y1] = board[x2][y2]; 
board[x2][y2] = temp; 
+0

另一个错误谢谢!我在代码中发现了另一个错误,你会介意阅读我的更新吗? – JavaLeave

+0

你可以尝试将'currentCol'和'currentRow'变量放到-1或0之类的东西上,这很难从示例代码中说出来。最好的办法是用调试器遍历代码并检查变量的状态 – MadProgrammer

+0

只有当我点击重置按钮后,移动才会失败。其他方法也是正确的 – JavaLeave

5

虽然我相信答案是显而易见的,我不真的不想告诉你。

相反,我建议你学习如何调试。

有一个像Eclipse这样的现代IDE,可以有一个单元测试或一个小应用程序,并打开调试模式并运行你的代码。

在for循环中添加一个断点,逐步遍历它,并检查变量和board的更改。你会很容易地知道答案。 “