Finite State Machine for Games Fall 2012 Ref: Chenney, CS679 lectures AI Game Programming Wisdom 2
Fall Outline AI and Game Introduction/examples Design Intuition State-based Implementation Extending Stack-based Fuzzy-state machine
Fall What is AI? (and is NOT) AI is the control of non-human entities in a game The other cars in a car game The opponents and monsters in a shooter Your units, your enemy ’ s units and your enemy in a RTS game But, typically does not refer to passive things that just react to the player and never initiate action That ’ s physics or game logic For example, the blocks in Tetris are not AI, nor is a flag blowing in the wind
Fall AI in the Game Loop AI is updated as part of the game loop, after user input, and before rendering
Fall AI Module AI Update Step The sensing phase determines the state of the world May be very simple - state changes all come by messaging Or complex - figure out what is visible, where your team is, etc The thinking phase decides what to do given the world The core of AI The acting phase tells the animation what to do Game Engine Sensing Thinking Acting
Fall AI by Polling Senses: looks to see what has been changed in the world then acts on it Generally inefficient and complicated Different characters might require different polling rate AI gets called at a fixed rate
Event Driven AI Events triggered by a message basically, a function gets called when a message arrives, just like a user interface) Example messages: You have heard a sound Someone has entered your field of view A certain amount of time has passed, so update yourself Fall does everything in response to events in the world
Fall AI Techniques in Games Basic problem: Given the state of the world, what should I do? A wide range of solutions in games: Finite state machines, Decision trees, Rule based systems, Neural networks, Fuzzy logic A wider range of solutions in the academic world: Complex planning systems, logic programming, genetic algorithms, Bayes-nets Typically, too slow for games
Fall Expressiveness What behaviors can easily be defined, or defined at all? Propositional logic: Statements about specific objects in the world – no variables Jim is in room7, Jim has the rocket launcher, the rocket launcher does splash damage Go to room8 if you are in room7 through door14 Predicate Logic: Allows general statement – using variables All rooms have doors All splash damage weapons can be used around corners All rocket launchers do splash damage Go to a room connected to the current room
Fall Finite State Machines (FSMs) A set of states that the agent can be in Connected by transitions that are triggered by a change in the world Normally represented as a directed graph, with the edges labeled with the transition event Ubiquitous in computer game AI
Fall Formal Definitions (N. Philips) "An abstract machine consisting of a set of states (including the initial state), a set of input events, a set of output events, and a state transition function. The function takes the current state and an input event and returns the new set of output events and the next state. Some states may be designated as "terminal states". The state machine can also be viewed as a function which maps an ordered sequence of input events into a corresponding sequence of (sets of) output events. Finite State Automaton: the machine with no output
Fall FSM with Output: vending machines OJ & AJ for 30 cents State table
Fall Vending Machine: state diagram
Fall FSM and Game Game character behavior can be modeled (in most cases) as a sequence of different “ mental state ”, where change is driven by the actions of player/other characters, … Natural choice for defining AI in games
Fall FSM Examples
Fall
Fall
Fall
PacMan State Machine Fall PacMan eats a Power Pill Timer <= 0 Collision with PacMan Timer <= 0 Collision with GhostBox
Actions of States Fall Roam; If PacMan gets close, PathTo (PacMan) Timer--; PathAwayFrom (PacMan) PathTo (GhostBox) Timer— Move back-and-forth
Fall Ex: predator vs. prey Prey (laalaa) Idle (stand,wave, … ) Flee (run) Sees predator No more threat captured Dead
Fall Predator (Raptor) Idle (stand) Hungry (wander) Pursuit (run) T idle > 5 Prey in sight T pursuit > 10 Dining Prey captured T dining >5
Fall Idling LaaLaa Stand Wave Wander (set random target) 50% 30% 20% Target arrived T wave >2 R T stand >4 This page illustrates: hierarchical state, Non-deterministic state transition This page illustrates: hierarchical state, Non-deterministic state transition
FSM Design
Fall Quake2 Examples Quake2 uses 9 different states: standing, walking, running, dodging, attacking, melee, seeing the enemy, idle and searching. Incomplete design Intuitive thinking: model the events and state changes
Fall Quake: Rocket
Fall Shambler monster
Fall FSM Advantages Very fast – one array access Expressive enough for simple behaviors or characters that are intended to be “ dumb ” Can be compiled into compact data structure Dynamic memory: current state Static memory: state diagram – array implementation Can create tools so non-programmer can build behavior Non-deterministic FSM can make behavior unpredictable
Fall FSM Disadvantages Number of states can grow very fast Exponentially with number of events: s=2 e Number of arcs can grow even faster: a=s 2 Propositional representation Difficult to put in “ pick up the better powerup ”, “ attack the closest enemy ” Expensive to count: Wait until the third time I see enemy, then attack Need extra events: First time seen, second time seen, and extra states to take care of counting
FSM Control System Implementation
Fall FSM Implementation
Fall Previous Example
Fall Code 1 Ad hoc implementation
Fall Code 1p
Fall Code 2 Structure, Readable, maintainable
Fall Hierarchical …
FSM Extensions
Advanced Issues Hierarchical FSM Non-deterministic FSM Swapping FSM Fall
Fall Hierarchical FSMs What if there is no simple action for a state? Expand a state into its own FSM, which explains what to do if in that state Some events move you around the same level in the hierarchy, some move you up a level When entering a state, have to choose a state for its child in the hierarchy Set a default, and always go to that Or, random choice Depends on the nature of the behavior
Fall Stack-based FSM History stack: Remember previous state; create characters with a memory … Pushdown automaton (PDA)
Fall Goal-based vs. State-based There is also a slight derivative to the state- based engine, but it used in more complicated games like flight simulators and games like MechWarrior. They use goal - based engines - each entity within the game is assigned a certain goal, be it 'protect base', 'attack bridge', 'fly in circles'. As the game world changes, so do the goals of the various entities.
Fall Processing Models Polling FSM update frequency Easy to implement and debug Inefficiency (Little Red example) Event-driven Publish-subscribe messaging system Game engine sends event messages to individual FSMs An FSM subscribes only to the events that have the potential to change the current state Higher efficiency, non- trivial implementation
Fall Efficiency and Optimization In AI, FSM is the most efficient technology available Yet, there is always room for improvement Level of Detail: depending on the condition (e.g., distance with player), use different FSM, or different update frequency
Fall References Web references: games.htm games.htm csr.uvic.ca/~mmania/machines/intro.htm /doc/design_principles/fsm.html /doc/design_principles/fsm.html Game Programming Gems Sections 3.0 & 3.1 It ’ s very very detailed, but also some cute programming
Well, the sad news … Fall Behavior trees
Fall
Additional Materials Fall
Fall Intuitive Design Say, a simple teletube baby has three states: idle, run, and wave Scenario: When an idle laalaa sees a butterfly, it waves to it. When the butterfly flies away, it returns to idle When an idle laalaa sees a mouse, it flees away. When the mouse is no longer in sight, it returns to idle
Fall Laalaa idle flee wave mouse ~mouse ~butterfly butterfly How to make sure the design complete? I.e., all states and transitions are considered Is there any systematic way to develop an FSM?
Fall Quake Bot Example (first-cut) Types of behavior to capture: Wander randomly if don ’ t see or hear an enemy When see enemy, attack When not see enemy and hear an enemy, chase enemy When die, re-spawn (new a bot from start) Events: see enemy, hear enemy, die States: wander, attack, chase, spawn
Fall Remark With 3 events, potentially there should be 2 3 states: (E,S,D)=(0,0,0),(1,0,0),(0,1,0), …,(1,1,1) Some doesn ’ t make sense E.g., ESD = 111 Name and create a state for the ones that we want to consider Wander (ESD=000) Chase (ESD=010) Attack (ESD=1x0), x for dont-care Die (ESD=xx1)
Fall FSM (first-cut) Events: E: see an enemy S: hear a sound D: die States: E: enemy in sight S: sound audible D: dead D ~E E D ~S S D ESD Problem: Can’t go directly from attack to chase. Why not? Spawn xx1 Wander 000 Attack 1x0 Chase 010 start
Fall FSM (first-cut) Events: E: see an enemy S: hear a sound D: die States: E: enemy in sight S: sound audible D: dead D ~E E D ~S S D ESD Spawn xx1 Wander 000 Attack 100 Chase 010 start E Attack+S 110 ~E ~S S D Extra state needs to be defined
Fall Quake Bot Example (refined) Types of behavior to capture: Wander randomly if don ’ t see or hear an enemy When see enemy, attack When not see enemy and hear an enemy, chase enemy When die, respawn Extensions: When health is low and see an enemy, retreat When see power-ups during wandering, collect them [hierarchical FSM]
Fall Example FSM with Retreat Spawn D (-E,-S,-L) Wander -E,-D,-S,-L E -S Attack-E E,-D,-S,-L E Chase -E,-D,S,-L S D S D D Retreat-E E,-D,-S,L L -E Retreat-S -E,-D,S,L Wander-L -E,-D,-S,L Retreat-ES E,-D,S,L Attack-ES E,-D,S,-L E E -E -L S -S L -E E L -L L D States: –E: enemy in sight –S: sound audible –D: dead –L: Low health A lot more states got added
Fall Hierarchical FSM Example Note: This is not a complete FSM All links between top level states still exist Need more states for wander Start Turn Right Go-through Door Pick-up Powerup Wander Attack Chase Spawn ~E E ~S S D ~E
Fall Non-Deterministic Hierarchical FSM (Markov Model) Adds variety to actions Have multiple transitions for the same event Label each with a probability that it will be taken Randomly choose a transition at run-time Markov Model: New state only depends on the previous state Attack Start Approach Aim & Jump & Shoot Aim & Slide Left & Shoot Aim & Slide Right & Shoot