简体   繁体   English

游戏期间在后台运行计数器线程

[英]Running a counter thread in the background during a game

I am wondering the best way to keep a timer going in the background while a game is played. 我想知道在玩游戏时保持计时器在后台运行的最佳方法。

I am programming a version of the HiLo game (in Java), which gives a user a certain amount of time to determine a number. 我正在编程HiLo游戏的一个版本(用Java),该版本可以给用户一定的时间来确定数字。 If a guess is not correct, the game will tell the user whether the name is too high or too low. 如果猜测不正确,则游戏会告诉用户名称是否太高或太低。

I'm keeping track of time using System.currentTimeMillis() and seeing how much time has elapsed. 我正在使用System.currentTimeMillis()跟踪时间,并查看已消耗了多少时间。 This seems to work well, and so far I have been checking to see how much time has elapsed each time a new number is entered. 这似乎工作得很好,到目前为止,我一直在检查每次输入新的数字已经花费了多少时间。 For example, currently the app output looks like this: 例如,当前应用程序输出如下所示:

  Welcome to HiLo! 
  You have 10 seconds to guess a number I'm thinking of between 1 and 100.

  > 67 
  Too high.

  > 29
   Too low.

  Half of your time is gone! Only 5 seconds remains!

  > 37
  Too high.

  > 33

  Oops! Time is up - try again.

As you can see, currently, it can only check when I enter a new number how much time is passed. 如您所见,目前,它只能检查我输入新数字时经过了多少时间。

I have tried creating a thread to start with a timer, however, when I start it, it keeps counting until the time is exhausted, without going on to the thread.run(int guess) which will be run when there is a new guess. 我曾尝试创建一个以计时器开始的线程,但是,当我启动它时,它会一直计数直到时间用完,而不会继续执行thread.run(intguess),当有新的猜测时它将运行。 I want to be able to still make guesses while the counter runs. 我希望计数器运行时仍能做出猜测。 Here is my attempt at a new implementation for thread.start(): 这是我对thread.start()的新实现的尝试:

public void start(int time_sent) throws InterruptedException {
    time = time_sent; 

    startTime = (System.currentTimeMillis() / 1000);

    while (1==1) {
        long elapsed = ((System.currentTimeMillis() / 1000) - (startTime));
        if (elapsed >= (time)) {
            System.out.println("Oops! Time is up - try again.");
            System.exit(0);
        }
        else if (elapsed >= (time/2) && !halfWarning) {
            System.out.println("Half of your time is gone! Only " + (time/2) + " seconds remains!");
            halfWarning = true;
        }
    }

}

How can I continue running this counter in the background? 如何在后台继续运行此计数器?

Use a ScheduledExecutorService to execute concurrent actions in the future: 将来使用ScheduledExecutorService执行并发操作:

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> half = ses.schedule(new Runnable() {
    @Override
    public void run() {
        System.out.println("Half of your time is gone!");
    }
}, time / 2, TimeUnit.SECONDS);
ScheduledFuture<?> full = ses.schedule(new Runnable() {
    @Override
    public void run() {
        System.out.println("Oops! Time is up - try again.");
        // System.exit(0) ?
    }
}, time, TimeUnit.SECONDS);

// check
if (input == toGuess) {
    half.cancel();
    full.cancel();
}

This is one more approach: 这是另一种方法:

public void game() {

    Scanner scanner = new Scanner(System.in);

    int time = 10; // sec

    message("You have " + time + " seconds to guess...");
    new Thread(new Background(System.currentTimeMillis() / 1000, time)).start();

    while (true) {
        String s = scanner.next();

        if (s.equals("55")) {
            message("You win");
            System.exit(0);
        } else {
            message("try again...");
        }
    }

}

private void message(String str) {
    System.out.println(str);
    System.out.print("> "); // monit
}

You start 1 thread with behavior implemented in Background class. 您以在Background类中实现的行为开始1个线程。 Next you enter while loop to capture user inputs. 接下来,输入while循环以捕获用户输入。 The Background thread works in background... 后台线程在后台工作...

private class Background implements Runnable {

    private long startTime;
    private long time;
    private boolean halfWarning;

    private Background(long startTime, long time) {
        this.startTime = startTime;
        this.time = time;
    }

    @Override
    public void run() {

        while (true) {
            long now = System.currentTimeMillis() / 1000;
            long elapsed = now - startTime;

            if (elapsed >= (time / 2) && !halfWarning) {
                message("\n Half of your time is gone! Only " + (time / 2) + " seconds remains!");
                halfWarning = true;
            }

            if (elapsed >= time) {
                message("\n Oops! Time is up - try again.");
                System.exit(0);
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                //ignore
            }
        }
    }
}

您可能有一个Timer线程,可以打印出这些消息并关闭监听程序。

It might inspire you : 它可能会启发您:

public static class Game extends TimerTask {
    private long    start;
    private long    end;

    public Game(long end) {
        super();
        this.start = System.currentTimeMillis();
        this.end = end;
    }

    @Override
    public void run() {
        while (System.currentTimeMillis() - start < end)
            System.out.println(System.currentTimeMillis());
    }
}

public static void main(String[] args) {
    TimerTask task = new Game(10000);
    Timer timer = new Timer();
    timer.schedule(task,0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM