Artificial Intelligence For Gam Es: Shashwat Shukla
Artificial Intelligence For Gam Es: Shashwat Shukla
es
Shashwat Shukla
Introduction to Artificial Intelligence (
AI)
• Many applications for AI
– Computer vision, natural language processing, speech
recognition, search …
• But games are some of the more interesting
• Opponents that are challenging, or allies that are
helpful
– Unit that is credited with acting on own
• Human-level intelligence too hard
– But under narrow circumstances can do pretty well (
ex: chess and Deep Blue)
– For many games, often constrained (by game rules)
• Artificial Intelligence (around in CS for some time
)
AI for CS different than AI for Games
• Introduction (done)
• MinMax (next)
• Agents
• Finite State Machines
• Common AI Techniques
• Promising AI Techniques
MinMax - Links
• Max’s turn
• Would like the “9” points (the
maximum)
• But if choose left branch, Min 5 Max
will choose move to get 3
left branch has a value 3 4 5 Min
of 3
• If choose right, Min can choo
se any one of 5, 6 or 7 (will ch 3 9 4 5 6 7 Max
oose 5, the minimum)
right branch has a valu
e of 5
• Right branch is largest (the m
aximum) so choose that move
MinMax – Second Example
Max
Min
Max
Min
• Max’s turn
• Circles represent Max, Squares represent Min
• Values inside represent the value the MinMax algorithm
• Red arrows represent the chosen move
• Numbers on left represent tree depth
• Blue arrow is the chosen move
MinMax and Chess
• With full tree, can determine best possible move
• However, full tree impossible for some games! Ex: Chess
– At a given time, chess has ~ 35 legal moves. Exponential gro
wth:
• 35 at one ply, 352 = 1225 at two plies … 356 = 2 billion and 3510
= 2 quadrillion
– Games can last 40 moves (or more), so 3540 … Stars in unive
rse: ~ 228
• For large games (Chess) can’t see end of the game. Must estima
te winning or losing from top portion
– Evaluate() function to guess end given board
– A numeric value, much smaller than victory (ie- Checkmate f
or Max will be one million, for Min minus one million)
• So, computer’s strength at chess comes from:
– How deep can search
– How well can evaluate a board position
– (In some sense, like a human – a chess grand master can eva
luate board better and can look further ahead)
MinMax – Pseudo Code (1 of 3)
• Introduction (done)
• MinMax (done)
• Agents (next)
• Finite State Machines
• Common AI Techniques
• Promising AI Techniques
Game Agents
• Expert Knowledge
– Finite State Machines, decision trees, … (FSM most pop
ular, details next)
– Appealing since simple, natural, embodies common sense
and knowledge of domain
• Ex: See enemy weaker than you? Attack. See enemy st
ronger? Go get help
– Trouble is, often does not scale
• Complex situations have many factors
• Add more rules, becomes brittle
– Still, often quite adequate for many AI tasks
• Many agents have quite narrow domain, so doesn’t matter
Game Agents – Thinking (3 of 3)
• Search
– Look ahead and see what move to do next
• Ex: piece on game board (MinMax), pathfinding
(A*)
– Works well with known information (ie- can se
e obstacles, pieces on board)
• Machine learning
– Evaluate past actions, use for future action
– Techniques show promise, but typically too slo
w
Game Agents – Acting (1 of 2)
• Introduction (done)
• MinMax (done)
• Agents (done)
• Finite State Machines (next)
• Common AI Techniques
• Promising AI Techniques
Finite State Machines
W
an
der A
tta
ck
N
oEn
emy
No (Do detailed
Ene
my
lth
Hea
example next
Low
F
le
e
slide)
Close by
Far away
– When player is close, search
– When see player, chase
• Make separate states
– Define behavior in each state Searching
• Wander – move slowly, rando
mly
Hidden
•
Visible
Search – move faster, in line
s
• Chasing – direct to player
• Define transitions Chasing
– Close is 100 meters (smell/se
nse)
– Visible is line of sight
Finite State Machines – Example (2 of 2)
Close by
Far away
• Behavior
– Move away from playe
r fast Searching Afraid
• Transition
– When player gets sca
Hidden
Visible
rab
– When timer expires
• Can have sub-states Chasing
– Same transitions, but di
fferent actions
• ie- range attack vers
us melee attack
Finite-State Machine: Approaches
• Three approaches
– Hardcoded (switch statement)
– Scripted
– Hybrid Approach
Finite-State Machine:
Hardcoded FSM
void Step(int *state) { // call by reference since state can change
switch(state) {
case 0: // Wander
Wander();
if( SeeEnemy() ) { *state = 1; }
break;
case 1: // Attack
Attack();
if( LowOnHealth() ) { *state = 2; }
if( NoEnemy() ) { *state = 0; }
break;
case 2: // Flee
Flee();
if( NoEnemy() ) { *state = 0; }
break;
}
}
Finite-State Machine:
Problems with switch FSM
1. Code is ad hoc
– Language doesn’t enforce structure
2. Transitions result from polling (checking e
ach time)
– Inefficient – event-driven sometimes bette
r
• ie- when damage, call “pain” event for monste
r and it may change states
3. Can’t determine 1st time state is entered
4. Can’t be edited or specified by game desig
ners or players
Finite State Machine
Alternative Implementation
• Make objects
• Transitions are events (passed by objects c
reating events)
– Ex: player runs. All objects within hearing r
ange get “run sound” event
• Each object can have step event
– Gets mapped to right action in state by call
back
Finite-State Machine:
Scripted with Alternative Language
AgentFSM {
State( STATE_Wander )
OnUpdate
Execute( Wander )
if( SeeEnemy ) SetState( STATE_Attack )
OnEvent( AttackedByEnemy )
SetState( Attack )
State( STATE_Attack )
OnEnter
Execute( PrepareWeapon )
OnUpdate
Execute( Attack )
if( LowOnHealth ) SetState( STATE_Flee )
if( NoEnemy ) SetState( STATE_Wander )
OnExit
Execute( StoreWeapon )
State( STATE_Flee )
OnUpdate
Execute( Flee )
if( NoEnemy ) SetState( STATE_Wander )
}
Finite-State Machine:
Scripting Advantages
1. Structure enforced
2. Events can be handed as well as polling
3. OnEnter and OnExit concept exists
(If objects, when created or destroyed)
4. Can be authored by game designers
– Easier learning curve than straight C/C++
Finite-State Machine:
Scripting Disadvantages
• Not trivial to implement
• Several months of development of language
– Custom compiler
• With good compile-time error feedback
– Bytecode interpreter
• With good debugging hooks and support
• Scripting languages often disliked by users
– Can never approach polish and robustness of comme
rcial compilers/debuggers
Finite-State Machine:
Hybrid Approach
• Use a class and C-style macros to approximate a scripting lan
guage
• Allows FSM to be written completely in C++ leveraging existi
ng compiler/debugger
• Capture important features/extensions
– OnEnter, OnExit
– Timers
– Handle events
– Consistent regulated structure
– Ability to log history
– Modular, flexible, stack-based
– Multiple FSMs, Concurrent FSMs
• Can’t be edited by designers or players
Finite-State Machine:
Extensions
• Many possible extensions to basic FSM
– Event driven: OnEnter, OnExit
– Timers: transition after certain time
– Global state with sub-states (same transitions, diff
erent actions)
– Stack-Based (states or entire FSMs)
• Easy to revert to previous states
• Good for resuming earlier action
– Multiple concurrent FSMs
• Lower layers for, say, obstacle avoidance – high priori
ty
• Higher layers for, say, strategy
AI for Games – Mini Outline
• Introduction (done)
• MinMax (done)
• Agents (done)
• Finite State Machines (done)
• Common AI Techniques (next)
• Promising AI Techniques
Common Game AI Techniques (1 of 4)
• Movement (continued)
– A* pathfinding
• Cheapest path through environment
• Directed search exploit knowledge about destination t
o intelligently guide search
• Fastest, widely used
• Can provide information (ie- virtual breadcrumbs) so c
an follow without recompute
• See: http://www.antimodal.com/astar/
– Obstacle avoidance
• A* good for static terrain, but dynamic such as other
players, choke points, etc.
• Example – same path for 4 units, but can predict collis
ions so furthest back slow down, avoid narrow bridget,
etc.
Common Game AI Techniques (3 of 4)
• Behavior organization
– Emergent behavior
• Create simple rules result in complex interactions
• Example: game of life, flocking
– Command hierarchy
• Deal with AI decisions at different levels
• Modeled after military hierarchy (ie- General does strategy
to Foot Soldier does fighting)
• Example: Real-time or turn based strategy games -- overall
strategy, squad tactics, individual fighters
– Manager task assignment
• When individual units act individually, can perform poorly
• Instead, have manager make tasks, prioritize, assign to unit
s
• Example: baseball – 1st priority to field ball, 2nd cover first b
ase, 3rd to backup fielder, 4th cover second base. All player
s try, then disaster. Manager determines best person for e
ach. If hit towards 1st and 2nd, first baseman field ball, pitc
her cover first base, second basemen cover first
Common Game AI Techniques (4 of 4)
• Influence map
– 2d representation of power in game
– Break into cells, where units in each cell are summed up
– Units have influence on neighbor cells (typically, decreas
e with range)
– Insight into location and influence of forces
– Example – can be used to plan attacks to see where enem
y is weak or to fortify defenses. SimCity used to show fi
re coverage, etc.
• Level of Detail AI
– In graphics, polygonal detail less if object far away
– Same idea in AI – computation less if won’t be seen
– Example – vary update frequency of NPC based on positio
n from player
AI for Games – Mini Outline
• Introduction (done)
• MinMax (done)
• Agents (done)
• Finite State Machines (done)
• Common AI Techniques (done)
• Promising AI Techniques (next)
– Used in AI, but not (yet) in games
– Subset of what is in book
Promising AI Techniques (1 of 3)
• Bayesian network
– A probabilistic graphical model with variables and probabl
e influences
– Example - calculate probability of patient having a specifi
c disease given symptoms
– Example – AI can infer if player has warplanes, etc. base
d on what it sees in production so far
– Can be good to give “human-like” intelligence without chea
ting or being too dumb
• Decision tree learning
– Series of inputs (usually game state) mapped to output (u
sually thing want to predict)
– Example – health and ammo predict bot survival
– Modify probabilities based on past behavior
– Example – Black and White could stroke or slap creature.
Learned what was good and bad.
Promising AI Techniques (2 of 3)
• Filtered randomness
– Want randomness to provide unpredictability to AI
– But even random can look odd (ie- if 4 heads in a ro
w, player think something wrong. And, if flip coin 10
0 times, will be streak of 8)
• Example – spawn at same point 5 times in a row, then
bad
– Compare random result to past history and avoid
• Fuzzy logic
– Traditional set, object belongs or not.
– In fuzzy, can have relative membership (ie- hungry,
not hungry. Or “in-kitchen” or “in-hall” but what if o
n edge?)
– Cannot be resolved by coin-flip
– Can be used in games – ie- assess relative threat
Promising AI Techniques (3 of 3)
• Genetic algorithms
– Search and optimize based on evolutionary principles
– Good when “right” answer not well-understood
– Example – may not know best combination of AI settings.
Use GA to try out
– Often expensive, so do offline
• N-Gram statistical prediction
– Predict next value in sequence (ie- 1818180181 … next will
probably be 8)
– Search backward n values (usually 2 or 3)
– Example
• Street fighting (punch, kick, low punch…)
• Player does low kick and then low punch. What is next?
• Uppercut 10 times (50%), low punch (7 times, 35%), sideswi
pe (3 times, 15%)
• Can predict uppercut or, proportionally pick next (ie- roll dic
e)
Summary