制作在给定间隔内自动运行的代码 [英] Making code that runs automatically within a given interval

查看:55
本文介绍了制作在给定间隔内自动运行的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些关于让代码在给定时间间隔内自动运行的问题.我正在编写一种游戏模式,它检查玩家是否已经杀死了地图上的所有怪物(我有我的方法).我想知道编程此检查的最佳方法是什么?我已经查找了一个人在类构造函数期间创建 ScheduledExecutorService 的方法......

I have a few questions about having code that runs automatically within a given interval. I'm programming a kind of game mode where it checks if the players have killed all the monsters in the map (I have my methods for these). I was wondering what's the best way to program this check? I've looked up ways where a person made a ScheduledExecutorService during a class constructor....

private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

但是我在网上看到有人用过

But I saw online where people used

static void main(String[] args) {

还有一个运行方法来进行检查.哪个会更好?我只是想每隔几秒左右运行一次检查,看看玩家是否已经清除了地图,如果他或她已经清除了,则进入下一阶段.

And a run method to do the checks. Which would be better? I'm simply wanting to have a check that runs every few or so seconds that sees if the player has cleared the map, and if he or she has, then to progress to the next stage.

推荐答案

我认为每次玩家杀死怪物时你都可以检查一下.也许您想收听 KillMonster 事件.您可以创建接口并在其他类中实现它.

I think you can check this every time the player kills a monster. Maybe you want to listen to a KillMonster event. You can create interfaces and implement that in your other class.

public interface KillMonsterEventListener {
    void onKillMonster ();
}

然后在播放器类中您可以调用一个方法来调用所有事件侦听器的onKillMonster().我想你知道怎么做.只需创建一个 KillMonsterEventListener 列表并使用如下方法:

And then in the player class you can call a method to call onKillMonster() of all the event listeners. I think you know how to do that. Just create a list of KillMonsterEventListeners and have a method like:

public void addKillMonsterEventListener (KillMonsterEventListener listener) {
    listeners.add (listener); //listeners is the list of KillMonsterEventListeners.
}

这篇关于制作在给定间隔内自动运行的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆