我正在用Java制作俄罗斯方 block ...我能够让单个俄罗斯方 block 图 block 移动得很好...但是如果我尝试将整个图 block (由多个图 block 组成)移动,则任何图 block 移动到当前存在的图 block (当前俄罗斯方 block )的位置被设置为 null。
我的目标是:
1) 计算所有图 block 的新位置(现在仅使用 2 个图 block 进行测试)
if (keycode == KeyEvent.VK_DOWN) {
newX = tile.getX(); //tile x
newY = tile.getY()+1; //tile y
newX2 = tile2.getX(); //tile 2 x
newY2 = tile2.getY()+1; //tile 2 y
2)将棋盘上的当前图 block 设置为空(基本上,从棋盘上拾取所有图 block )
board.setTileAt(null, tile.getX(), tile.getY());
board.setTileAt(null, tile2.getX(), tile2.getY());
Board的setTileAt方法供引用:
public void setTileAt(Tile tile, int x, int y) {
grid[x][y] = tile;
}
3) 执行有效的移动检查(移动是否在边界内?并且... grid[x][y] 是否为空?)
4) 最后,如果有效,将图 block 放回到板上的新位置
tile.setLocation(newX, newY);
tile2.setLocation(newX2, newY2);
<小时/>
输出:
Game running...
original: 1, 1
new: 1, 2
original: 1, 2
new: 1, 3
有什么想法吗?我从棋盘上拾取棋子的各个棋子,然后将它们替换到新位置的逻辑是否正确?
谢谢!
<小时/>编辑:
向 Board 类添加了有效的移动检查:
在界限内吗?
public boolean isValidCoordinate(int x, int y) {
return x >= 0 && y >= 0 && x < width && y < height;
}
有空位吗?
public boolean isOpen(int x, int y) {
return isValidCoordinate(x, y) && getTileAt(x, y) == null;
}
在 Piece 类上,如果 isOpen 为 true,我将当前图 block 位置设置为 null...另外,我设置新位置...
public void move(int keycode) {
//move
int newX, newY, newX2, newY2;
if (keycode == KeyEvent.VK_DOWN) {
newX = tile.getX();
newY = tile.getY()+1;
newX2 = tile2.getX();
newY2 = tile2.getY()+1;
if (board.isOpen(newX2, newY2) && board.isOpen(newX, newY)) {
board.setTileAt(null, tile.getX(), tile.getY());
board.setTileAt(null, tile2.getX(), tile2.getY());
System.out.println("original: " + tile.getX() + ", " + tile.getY());
System.out.println("new: " + newX + ", " + newY);
System.out.println("original: " + tile2.getX() + ", " + tile2.getY());
System.out.println("new: " + newX2 + ", " + newY2);
tile.setLocation(newX, newY);
tile2.setLocation(newX2, newY2);
}
}
}
最佳答案
您的步骤正确,但顺序错误。
计算所有图 block 的新位置(现在仅使用 2 个图 block 进行测试)
执行有效的移动检查(移动是否在边界内?并且... grid[x][y] 是否为空?)
如果有效,则将棋盘上的当前图 block 设置为空(基本上,从棋盘上拾取所有图 block )
最后,如果有效,请将图 block 放回板上的新位置
关于java - 俄罗斯方 block ,移动一 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15666480/