【发布时间】:2014-12-09 17:52:54
【问题描述】:
我有一件事有问题。我有一张 10 个城市和一个平民的地图。我希望平民随机地从一个城市走到另一个城市。但问题是这座城市正在不断地被选择,所以平民在到达之前就改变了目的地。这是我绘制所有内容的 Jpanel 代码的一部分:
@Override
public void run() {
while (running) {
update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
}
}
}
private void update() {
if (game != null && running == true) {
c.goTo(cities); // c is civilian
}
}
这是民用代码的一部分
private boolean set = true;
public void move(int x, int y) {
if (this.location.x != x || this.location.y != y) {
if (this.location.x > x) {
this.location.x -= 1;
} else {
this.location.x += 1;
}
if (this.location.y > y) {
this.location.y -= 1;
} else {
this.location.y += 1;
}
}
}
public void goTo(ArrayList<City> cities) {
City city;
if (set) {
city = cities.get(rand());
move(city.location.x, city.location.y);
set = false;
} else {
set = true;
}
}
public int rand() {
int i;
Random rand = new Random();
i = rand.nextInt(10);
return i;
}
如何解决?
【问题讨论】: