私は Java でテトリスを作成しています... 1 つのテトリス タイルをうまく動かすことができます... しかし、ピース全体 (複数のタイルで構成される) を動かそうとすると、どのタイルも(現在のテトリス ピースの) 現在存在するタイルの位置は null に設定されます。
私の目標はこれです:
1) すべてのタイルの新しい位置を計算します (テストのために今のところ 2 つのタイルを使用しています)
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) ボード上の現在のタイルを null に設定します (基本的に、ボードからすべてのタイルを拾います)。
board.setTileAt(null, tile.getX(), tile.getY());
board.setTileAt(null, tile2.getX(), tile2.getY());
参照用のボードの setTileAt メソッド:
public void setTileAt(Tile tile, int x, int y) {
grid[x][y] = tile;
}
3) 有効な移動チェックを実行します (範囲内で移動しますか? そして... grid[x][y] は null ですか?)
4) 最後に、有効な場合は、タイルをボードの新しい場所に戻します。
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 の場合、現在のタイルの場所を 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);
}
}
}