![](/img/trans.png)
[英]Java initial values and array access basic understanding - unusual output
[英]Understanding Array Access (Processing)
嗨,任何人都可以幫我理解這個Langton螞蟻素描中的這段特殊代碼。
antLoc = new int[]{rows/2,columns/2};
我並不完全理解這里實際發生了什么,這里是上下文的其余代碼。 (最初來自http://www.openprocessing.org/visuals/?visualID=13653 )
boolean[][] state;
int[] antLoc;
int antDirection;
int squareSize = 5;
int columns, rows;
color bgCol = color(0,128,128);
color antCol = color (255,0,0);
color sqCol = color(128,128,128);
void setup(){
size(800,600);
background(bgCol);
columns = width/squareSize;
rows = height/squareSize;
state = new boolean[rows][columns];
for(int j = 0; j < rows; j++){
for(int i = 0; i < columns; i++){
state[j][i] = false;
}
}
antLoc = new int[]{rows/2,columns/2};
antDirection = 1;
}
void drawScene(){
fill(sqCol);
for(int j = 0; j < rows; j++){
for(int i = 0; i < columns; i++){
if(state[j][i]){
rect(i*squareSize,j*squareSize,squareSize,squareSize);
}
}
}
fill(antCol);
rect(antLoc[1]*squareSize,antLoc[0]*squareSize,squareSize,squareSize);
}
void turnLeft(){
if (antDirection > 1){
antDirection--;
} else{
antDirection = 4;
}
}
void turnRight(){
if (antDirection < 4){
antDirection++;
} else {
antDirection = 1;
}
}
void moveForward(){
if (antDirection == 1){
antLoc[0]--;
}
if (antDirection == 2){
antLoc[1]++;
}
if (antDirection == 3){
antLoc[0]++;
}
if (antDirection == 4){
antLoc[1]--;
}
}
void updateScene(){
moveForward();
if (state[antLoc[0]][antLoc[1]] == false){
state[antLoc[0]][antLoc[1]] = true;
turnRight();
} else {
state[antLoc[0]][antLoc[1]] = false;
turnLeft();
}
}
void draw(){
background(bgCol);
drawScene();
for(int i = 0; i < 10; i++){
updateScene();
}
}
您的代碼創建一個長度為2的新int
數組,並使用給定的表達式初始化元素。 它相當於:
antLoc = new int[2];
antLoc[0] = rows/2;
antLoc[1] = columns/2;
你提到的那條線:
antLoc = new int[]{rows/2,columns/2};
大致類似於:
antLoc = new int[2];
antLoc[0] = rows / 2;
antLoc[1] = columns / 2;
為方便起見,它只是語法簡寫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.