我正在尝试为我的敌方舰船实现一个基本的游戏AI,使其执行随机动作(例如转向并射击,然后向前移动,然后可能掉头再射击等)。我已经制作了一个简单的AI,它只会旋转并射击。
这是RotateAndShoot AI的代码:
public class RotateAndShoot implements Controller {Action action = new Action();@Overridepublic Action action() { action.shoot = true; action.thrust = 1; //1=on 0=off action.turn = -1; //-1 = left 0 = no turn 1 = right return action;}}
这是Controller类的代码,如果有帮助的话可以参考:
public interface Controller {public Action action();}
这些代码使用了一个名为Action的类,该类提供了一些变量,这些变量被分配给动作(例如public int thrust,如果设置为开启状态,会使舰船向前移动)。我该如何实现一个只执行一系列随机动作的AI形式呢?
回答:
你可以使用Math.random()或Random类。
这是使用Random类的解决方案:
@Overridepublic Action action() { Random rand = new Random(); action.shoot = rand.nextBoolean(); action.thrust = rand.nextInt(2); action.turn = rand.nextInt(3) - 1; return action;}