如何创建ArrayList,以便我可以记录每个项目的位置?

时间:2015-12-07 23:21:17

标签: java arraylist

我正在尝试记录此代码中绘制的每个矩形的位置。我是初学者和我的理解,只能通过一个arraylist来完成。我不知道如何构建列表来记录矩形移动到的每个位置。这就是代码目前的样子。

Walker w;

void setup() {
  size(500, 500);
  w = new Walker();
  background(0);
  frameRate(15);
}

void draw() {
  w.draw();
}

void mousePressed(){
  w.mousePressed();
}

class Walker {
  int x;
  int y;
  float direction;

  Walker() {
    x = width/2;
    y = height/2;
  }

  void draw() {
    rect(x, y, 10, 10);

    if (direction<1) {    //North
      float choice = random(1);

      if (choice <0.4) {
        x=x+10;
      } else if (choice <0.8) {
        x=x-10;
      } else {
        y=y-10;
      }
    } else if (direction<2) {    //South
      float choice = random(1);

      if (choice <0.4) {
        x=x-10;
      } else if (choice <0.8) {
        x=x+10;
      } else {
        y=y+10;
      }
    } else if (direction<3) { // East
      float choice = random(1);

      if (choice < 0.4) {
        y=y+10;
      } else if (choice <0.8) {
        y=y-10;
      } else {
        x=x+10;
      }
    } else if (direction<4) { //West
      float choice = random(1);

      if (choice < 0.4) {
        y=y+10;
      } else if (choice <0.8) {
        y=y-10;
      } else {
        x=x-10;
      }
    }
  }
  void mousePressed() {
    direction = random(4);
    x = width/2;
    y = height/2;
  }
}

1 个答案:

答案 0 :(得分:0)

您需要在声明方向的位置创建一个ArrayList。

ArrayList<String> previousPoints = new ArrayList<String>();

以下是您需要的导入声明:

import java.util.ArrayList;

这不是最好的方法,但是每当你移动矩形时,给定x和y坐标,你可以将它们添加到ArrayList previousPoints中,如下所示:

previousPoints.add("" + x + "," + y);

如果您在previousPoints中有所需的索引,则可以检索x和y :(示例索引为3)

String[] points = (previousPoints.get(3)).split(",");
int newX = Integer.parseInt(points[0]);
int newY = Integer.parseInt(points[1]);

我希望这有助于Yianna!

编辑:重要 - &gt;进口

相关问题