对于我们的俄罗斯方块项目,我们有一个10x20的网格嵌套在一个400x800 JPanel中。将创建一个 Tetromino 类,该类具有一个在生成碎片时设置坐标的private int[] coordinate
public void spawnTetromino() {
...
int[] spawnCoordinate = new int[] {Y_VALUE, 5};
fallingTetromino.setCoordinate(spawnCoordinate);
....
if (!gameOver) {
projectTetromino(spawnCoordinate)
此处突出显示projectTetromino()
:
public void projectTetromino(int[] coordinate) {
// projects the shape of the tetromino onto the board based on its coordinate
// only projects the non-0 (the filled) indices of the shape
int[][] shape = fallingTetromino.getShape();
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
if (shape[y][x] != 0) {
grid[coordinate[0]+y][coordinate[1]+x] = shape[y][x];
}
}
}
}
创建了一个测试网格,它将输出如下内容:
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 1 1 1 0 0 0|
|0 0 0 0 0 1 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
|0 0 0 0 0 0 0 0 0 0|
我的工作是弄清楚如何在这个网格中实现图形。这是我目前拥有的代码
public void paintComponent(Graphics g) {
super.paintComponent(g);
tile = new Rectangle(tileX,tileY,tileWidth, tileHeight);
int[] tileCoordinate = {tileX, tileY};
Graphics2D g2 = (Graphics2D) g;
g2.setBackground(Color.BLACK);
//filling out the tiles
for (int x = 0; x <= 10; x++) {
tile.y = 0;
for (int y = 0; y <=20; y++) {
//check if the tetronimo shape is 0
tile.y = tile.y + 40;
int[] shape = fallingTetromino.getCoordinate();
//somehow check if tetromino is inside one of the tile????
g2.fill(tile);
}
tile.x = tile.x + 40;
}
}
我的最终目标是循环浏览这个图形网格并填写只有 Tetromino 占据它的图块(即非 0 图块(。我将如何处理这个问题?
图形中实现这一点,你需要在你的主游戏方法中有一个通用的游戏循环。因为您尝试移动对象,所以必须重新初始化它们(或更新它们的位置(。
我的猜测是安装 Java 编辑器并查看几个可用的对象。该程序将为您提供图形界面和实时代码更新,您只需要在普通 IDE 中复制即可。我的建议是绘制多边形或使用一个小对象(1 像素 x 1 像素(,然后为其着色。
Java 编辑器:在此处下载