【问题标题】:JAVA swing. movement from random point to random pointJAVA摇摆。从随机点移动到随机点
【发布时间】: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;
}

如何解决?

【问题讨论】:

    标签: java swing random


    【解决方案1】:

    那么,你的问题就在这里:

        while (running) {
        update();
        repaint();
        try {
            Thread.sleep(17);
        } catch (InterruptedException ex) {
        }
    }
    

    您每 17 毫秒调用一次更新,这反过来又导致您的平民每 17 毫秒移动到一个新城市。你可以做一个单独的语句来调用更新,而另一个布尔语句是错误的,这样你就只能在他在一个城市时旅行。

    例如:

    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 方法将被调用,随机选择一个新城市并让您的平民重新开始行动。

    【讨论】:

      猜你喜欢
      • 2013-09-30
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      相关资源
      最近更新 更多