java - 了解数组访问(处理)

标签 java arrays processing

嗨,有人可以帮助我理解兰顿 Ant 草图中的这段特定代码吗?

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();
  }

}

最佳答案

您提到的行:

antLoc = new int[]{rows/2,columns/2};

大致类似于:

antLoc = new int[2];
antLoc[0] = rows / 2;
antLoc[1] = columns / 2;

为了方便起见,这只是语法简写。

关于java - 了解数组访问(处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7805158/

相关文章:

java - 递归搜索错误

java - 使用具有多个字段的不同类型列表的流来断言等于

java - 我可以修改 char 数组中的一个元素,但无法修改另一个元素

java - 如何制作正在处理的游戏首页?

java - 如何从 EJB 使用 Web 服务

php - 关联数组php mysql

javascript - 比较 2 个可观察数组并使用 knockout 将匹配值插入第三个数组

console - 处理隐藏控制台警告

java - 二维数组中的加权随机数 - 处理

java - Cassandra 卡在 Initializing IndexInfo 上