【问题标题】:Decreasing hunger variable overtime using java使用java减少饥饿变量超时
【发布时间】:2020-09-13 18:59:13
【问题描述】:

我是一位经验丰富的 Python 程序员,第一次接触 Java,我正在尝试编写一个基于文本的冒险游戏。我希望游戏有一个 饥饿变量设置为 100,每 15 秒减少 5。 我尝试做一个 while 循环,但效果不佳。我在网上做了很多搜索,但没有找到任何答案。 这是我尝试过的

package game;
public class game {
    int hunger = 100;
    int hungerDecreaser = 5;
    while (true) {
        Thread.Sleep(15000);
        hunger - hungerDecreaser;
    }
}

【问题讨论】:

  • 向我们展示您迄今为止尝试过的代码。

标签: java game-development


【解决方案1】:

您必须捕获 Thread.sleep() 将抛出的 InterruptedException。 hunger - hungerDecreaser 也应该改为hunger -= hungerDecreaser

以下是如何实现并发的示例。

Main.java 文件:

public class Main {
    public static void main(String[] args) {
        //create hunger handler
        Runnable hunger = new Hunger();
        //create hunger thread
        Thread thread = new Thread(hunger);
        //start thread
        thread.start();

        //rest of game
        System.out.println("This code will run at the same time as the hunger thread.");
    }
}

Hunger.java 文件:

public class Hunger implements Runnable{
    int hunger;
    int hungerDecreaser;

    Hunger() {
        hunger = 100;
        hungerDecreaser = 5;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(15000); // throws InterruptedException
            } catch (InterruptedException e) { // Exception must be caught or else code will not compile
                Thread.currentThread().interrupt();
            }
            hunger -= hungerDecreaser;
            System.out.println("The hunger has decreased to: " + hunger);
        }
    }
}

【讨论】:

  • 谢谢,它帮了很多忙,但现在我的饥饿感下降了,我无法玩游戏。有没有办法让饥饿减少和游戏同时进行?
  • 那是因为 Thread.sleep() 暂停了 整个 线程(基本上是你的所有代码)。研究多线程编程以使多个线程同时运行。这是一个总体概述:What is a multi-threaded appplication?。查看Introduction to Java Threads 以获取特定于 Java 的概述。祝你好运!
  • 嗨,看到了你推荐给我的两个链接,但我仍然无法弄清楚一些事情......我是否必须创建两个线程并将“hungerdecreaser”放在其中之一他们和其他代码的其余部分?如果是这样,我该怎么做?假设剩下的代码是System.out.println("hello world");,是不是必须放到public static void run()中还是放到“extends Thread”中?
  • @Lalle 我已经用一个代码示例更新了答案,说明如何实现并发。
  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-12
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多