问题描述
所以我正在构建一个项目以构建俄罗斯方块风格的游戏,我希望能够测试该形状是否能够添加到 5 x 5 网格中。该形状由 2D 阵列建模,其中 1 被认为是形状的单个块(形状由几个块组成)。形状是用 3 x 3 网格建模的。我必须做的事情是检查网格的形状是否能够适合它。举个例子,在网格的顶部正方形放置一个线形,这条线会越界,不应该工作,或者另一个例子是网格上可能已经有一个形状,所以这条线应该不能放在上面。
这是我迄今为止得到的代码,它不起作用,我真的很难概念化要做什么。提前致谢。
请注意,cols 是网格中的列数 (5),而行数是相同的 (5)。游戏块是形状,坐标是用户点击 5x5 网格的位置。
另外:形状的锚点是 3x3 网格的 1,1(所以锚点正好在网格的中间)。而 get(int x,int y) 方法是获取存储在 5x5 网格中的值。
对不起,如果一开始没有说清楚,但我基本上是想看看存储在 3x3 网格(由块组成)中的形状是否可以放在 5x5 网格的顶部。包含块的 3x3 网格有一个中心锚点,所以它是 1,1(因为数组从 0 开始)。如果 5x5 网格有其他块与添加的新形状处于同一坐标,那么我希望它返回 false 或者如果形状在放置在 5x5 网格上时超出边界,但如果可以的话添加成功则返回true。
public boolean canPlayPiece (GamePiece piece,int x,int y) {
logger.info("canPlayPiece - Block clicked coordinates: " + x + "," + y);
// Piece co-ordinates are 3 x 3,each element that is 1 means there is a block there
int[][] pieceCoordinates = piece.getBlocks();
// For loop to iterate through the grid
// first looping through x values
for (int i = x - 1; i < cols; i++) {
System.out.println("i= " + i);
// nested for loop to find the y values stored inside the x
for (int j = y - 1; j < rows; j++) {
System.out.println("j: " + j);
if (pieceCoordinates[x][y] == 1 && get(i,j) != 0) {
logger.info("canPlayPiece: FALSE");
return false;
}
}
}
logger.info("canPlayPiece: TRUE");
return true;
}
解决方法
好的,我为你做了以下:
public boolean canPlayPiece(GamePiece piece,int x,int y) {
int[][] pc = piece.getBlocks();
final int w = 3,h = 3,e = w - 1;
final int offX = -1,offY = -1; // The offset of the left top corner from 'x' and 'y'
int i,si,ei,ax,ay,rx,ry;
for (ei = w * h - 1; ei >= 0 && pc[ei / w][ei % w] == 0; ei--);
for (si = 0; si <= ei && pc[si / w][si % w] == 0; si++);
for (i = si + 1,ax = si % w; ax > 0 && i <= ei; i++) if (pc[i / w][rx = i % w] != 0) { si += Math.min(rx - ax,0); ax = rx; }
for (i = ei - 1,ax = ei % w; ax < e && i >= si; i--) if (pc[i / w][rx = i % w] != 0) { ei += Math.max(rx - ax,0); ax = rx; }
if (si > ei) return true; // There is no block in the piece's grid
int sx = si % w,sy = si / w,ex = ei % w,ey = ei / w; // The bounds of the shape inside of pc
int asx = x + offX + sx,asy = y + offY + sy,aex = asx + ex - sx,aey = asy + ey - sy;
if ((asx | asy | aex | aey | cols - 1 - aex | rows - 1 - aey) < 0) return false; // Would be out of bounds
for (rx = sx,ax = asx; rx <= ex; rx++,ax++) {
for (ry = sy,ay = asy; ry <= ey; ry++,ay++) {
// if (grid[ay][ax] != 0 && pc[ry][rx] != 0) return false; // Block overlaps another block
if (get(ax,ay) != 0 && pc[ry][rx] != 0) return false; // Block overlaps another block
}
}
return true;
}
- 首先找出“pc”网格(由“piece.getBlocks()”返回的网格)内部形状的边界
- 如果 'pc' 中没有形状,它将返回 true,因为可以将一个空形状放置在任何地方(将返回值更改为 false,如果您想在这种情况下返回 false)
- 如果内部形状越界,插入时返回false
- 最后,它将遍历网格(使用您的“get(x: int,y: int)”函数)和“pc”来检查“pc”中的形状是否与网格内的任何预先存在的块重叠.如果不是,则返回 true。
我真的希望这对你有用。我测试了它,它至少对我有用。