[英]JAVA swing. movement from random point to random point
我有一件事有问题。 我有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;
}
怎么解决呢?
因此,您的问题在这里:
while (running) {
update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
}
}
您每17毫秒调用一次update,这反过来又导致您的平民每17毫秒移动一次新城市。 您可以编写一个单独的语句来调用update,而另一个布尔语句为false,以便仅当他在城市中时才旅行。
例如:
boolean travelling = //whatever you go about to configure this
while(travelling == false){
update();
}
这将导致他仅在不在城市时才旅行。 这是一些非常粗糙的代码(您必须根据自己的喜好配置它):
//civilian x //civilian y if(this.location.x == //randomed city.x && this.location.y == //randomed city.y){ travelling = false; }
这很可能需要放在第一组代码的run()
方法中,因此可以反复检查它。 但是,让我解释一下上面的代码在做什么:
首先,您有一个线程或其他线程在运行它,以检查您的平民的x和y是否对应于最近随机出现的城市的x和y,显然,当它们相同时,平民在该城市。
其次,当x和y相同时,该语句使travelling
假
第三,如果travelling
不正确,则会调用您的自定义update
方法,随机选择一个新城市,然后让平民回到行动中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.