Reputation: 12718
I'm making tetris in Java... I'm able to get a single tetris tile to move just fine... but if I try to move the piece as a whole (composed of multiple tiles), any tile moving into the position of a currently existing tile (of the current tetris piece) is set to null.
My goal is this:
1) Calculate new positions of all tiles (just using 2 tiles for now to test)
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) Set current tiles on the board to null (basically, pick all tiles up off the board)
board.setTileAt(null, tile.getX(), tile.getY());
board.setTileAt(null, tile2.getX(), tile2.getY());
Board's setTileAt method for reference:
public void setTileAt(Tile tile, int x, int y) {
grid[x][y] = tile;
}
3) Perform valid move checks (is move in bounds? and... is grid[x][y] null?)
4) Finally, if valid, set the tiles back on the board in the new location
tile.setLocation(newX, newY);
tile2.setLocation(newX2, newY2);
Output:
Game running...
original: 1, 1
new: 1, 2
original: 1, 2
new: 1, 3
Any thoughts? Is my logic for picking up the piece's individual tiles up off the board, then replacing them at a new location correct?
Thanks!
EDIT:
Added valid move checks to Board class:
In bounds?
public boolean isValidCoordinate(int x, int y) {
return x >= 0 && y >= 0 && x < width && y < height;
}
Is open spot?
public boolean isOpen(int x, int y) {
return isValidCoordinate(x, y) && getTileAt(x, y) == null;
}
On Piece class, I set the current tiles locations to null if isOpen is true... Also, I set new location...
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);
}
}
}
Upvotes: 0
Views: 1718
Reputation: 51553
You have the right steps, but the wrong order.
Calculate new positions of all tiles (just using 2 tiles for now to test)
Perform valid move checks (is move in bounds? and... is grid[x][y] null?)
If valid, set current tiles on the board to null (basically, pick all tiles up off the board)
Finally, if valid, set the tiles back on the board in the new location
Upvotes: 1