我有一个来自Java突破游戏教程的代码。代码的一部分是砖图。问题是我并不真正理解这段代码背后的逻辑,我不会只是复制代码。
我只知道用数组创建一个变量映射。之后,我将两个变量"row"和"col"放在这个数组中。问题是我不明白"map.lenght"。
import java.awt.*;
public class BrickMap {
int map[][];
int brickHeight;
int brickWigth;
public BrickMap(int row, int col){
map= new int [row][col];
for(int i = 0; i < map.length; i++){
for(int j = 0; j < map[0].length; j++){
map[i][j] = 1;
}
}
brickWigth = 640/col;
brickHeight = 170/row;
}
public void draw(Graphics2D g){
for(int i = 0; i < map.length; i++){
for(int j = 0; j < map[0].length; j++) {
if(map[i][j] > 0){
g.setColor(Color.ORANGE);
g.fillRect(j *brickWigth + 80, i *brickHeight + 50 , brickWigth, brickHeight);
g.setStroke(new BasicStroke(4));
g.setColor(Color.darkGray);
g.drawRect(j *brickWigth + 80, i *brickHeight + 50 , brickWigth, brickHeight);
}
}
}
}
public void setBrickValue(int value, int row, int col){
map[row][col] = value;
}
}
map
是一个二维数组。 map.length
指定由 row
定义的第一个维度的长度。 map[0].length
反过来指定第二维的第一个数组的长度。
map.length
返回数组中元素的数量。
map[0].length
返回 map 数组(二维(中第一个数组中的元素数。