AI 在 Java 游戏中每 n 秒执行一次随机动作
AI performing a random action every n seconds in Java Game
我正在实现一个游戏,其中敌人 AI 从预设数量的动作中执行随机动作。我实现了随机动作的执行,但这意味着游戏的每次更新都会执行一个新动作。例如,我希望 AI 每 1 秒执行一次操作。这将如何完成?这是我的随机操作代码:
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;
}
}
我假设您的应用程序对不同的对象重复调用 action()
方法,并且您只想每秒更改一次 RandomAction 行为,而不是在每次调用时都更改。你可以这样做:
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();
}
}
如您所见,仅当自上次更新后经过 1 秒后,操作才会使用随机值进行更新。之后更新时间变量设置为当前时间。
我正在实现一个游戏,其中敌人 AI 从预设数量的动作中执行随机动作。我实现了随机动作的执行,但这意味着游戏的每次更新都会执行一个新动作。例如,我希望 AI 每 1 秒执行一次操作。这将如何完成?这是我的随机操作代码:
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;
}
}
我假设您的应用程序对不同的对象重复调用 action()
方法,并且您只想每秒更改一次 RandomAction 行为,而不是在每次调用时都更改。你可以这样做:
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();
}
}
如您所见,仅当自上次更新后经过 1 秒后,操作才会使用随机值进行更新。之后更新时间变量设置为当前时间。