首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建ArrayList,以便记录每个项目的位置?

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

Stack Overflow用户
提问于 2015-12-07 23:21:17
回答 1查看 99关注 0票数 0

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

代码语言:javascript
复制
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;
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-08 00:13:24

您会想要创建一个ArrayList,在这里您声明了方向

代码语言:javascript
复制
ArrayList<String> previousPoints = new ArrayList<String>();

下面是您需要的import语句:

代码语言:javascript
复制
import java.util.ArrayList;

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

代码语言:javascript
复制
previousPoints.add("" + x + "," + y);

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

代码语言:javascript
复制
String[] points = (previousPoints.get(3)).split(",");
int newX = Integer.parseInt(points[0]);
int newY = Integer.parseInt(points[1]);

我希望这对伊安娜有帮助!

编辑:重要的->导入

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34145221

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档