简体   繁体   中英

AI performing a random action every n seconds in Java Game

Im implementing a game where an enemy AI performs a random action from a pre set amount of actions. Iv implemented the performing of a random action, but this means every single update of the game a new action is performed. Rather i would like the AI to perform an action every 1 second for example. How would this be done ? Here is my random action code:

public class RandomAction implements Controller {
    Action action = new Action();

    @Override
    public Action action() {

        Random rand = new Random();
        action.shoot = rand.nextBoolean();
        action.thrust = rand.nextInt(2);
        action.turn = rand.nextInt(3) - 1;
        return action;
    }

}

I assume thay your app calls action() method on different objects repeatedly and you want to change RandomAction behavior only once a second, not on every call. You can do this:

public class RandomAction implements Controller {
    Action action = new Action();
    Random rand = new Random();
    long updatedAt;

    public RandomAction() {
        updateAction(); // do first init
    }

    @Override
    public Action action() {            
        if (System.currentTimeMillis() - updatedAt > 1000) {
            updateAction();
        }            
        return action;
    }

    private void updateAction() {
        action.shoot = rand.nextBoolean();
        action.thrust = rand.nextInt(2);
        action.turn = rand.nextInt(3) - 1;
        updatedAt = System.currentTimeMillis();
    }
}

As you can see, action is updated with random values only if 1 second passed since last update. Update time variable is set to current time after that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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