Class AIBrain

java.lang.Object
com.codename1.gaming.platformer.AIBrain

public final class AIBrain extends Object

Enemy behaviour as a small state machine of actions and decisions, after Corgi Engine's AI Brain.

A brain does not move anything itself. Each tick it produces the Input bits its actor would get from a player, so an enemy runs on exactly the same abilities and collision as the hero, and is as deterministic. The current State runs its Action, then its transitions are tried in order and the first Decision that holds switches state.

import com.codename1.gaming.platformer.*;

Actor enemy = new Actor("slime", Fx.of(64), Fx.of(16), Fx.of(12), Fx.of(10));
AIBrain brain = new AIBrain();
AIBrain.State patrol = brain.addState("patrol", new AIBrain.Patrol());
AIBrain.State chase = brain.addState("chase", new AIBrain.Chase(true));
patrol.addTransition(new AIBrain.TargetWithin(Fx.of(96), true), chase);
chase.addTransition(new AIBrain.Not(new AIBrain.TargetWithin(Fx.of(160), false)), patrol);
enemy.setBrain(brain);
  • Constructor Details

    • AIBrain

      public AIBrain()
  • Method Details

    • addState

      public AIBrain.State addState(String name, AIBrain.Action action)

      Adds a state. The first one added is where the brain starts.

      Parameters
      • name: the name
      • action: what it does each tick
      Returns

      the state, to add transitions to

    • think

      public int think(Actor self, PlatformWorld world)

      Computes the actor's input for this tick. Called by PlatformWorld.

      Parameters
      • self: the actor
      • world: the world
      Returns

      Input bits

    • getCurrent

      public AIBrain.State getCurrent()

      The current state.

      Returns

      the state, or null for an empty brain

    • getTicksInState

      public int getTicksInState()

      Ticks spent in the current state.

      Returns

      the tick count

    • getDirection

      public int getDirection()

      The patrol direction, -1 or 1, shared by the stock actions.

      Returns

      the direction

    • setDirection

      public void setDirection(int d)

      Sets the patrol direction.

      Parameters
      • d: -1 or 1
    • ledgeAhead

      public static boolean ledgeAhead(Actor self, PlatformWorld world, int dir)

      Whether the cell ahead of an actor's feet has no floor.

      Parameters
      • self: the actor
      • world: the world
      • dir: -1 or 1
      Returns

      true at a ledge