AI Game Design: Problem-Solving Strategies
AI Game Design: Problem-Solving Strategies
Game Playing:
Optimal Decisions in Games, Alpha - Beta Pruning, Movement Planning.
Artificial Intelligence
Gaming Problem-Solving Approaches:
We will see several uninformed search algorithms—algorithms that are given no information about the problem other than
its definition. Although some of these algorithms can solve any solvable problem, none of them can do so efficiently.
Uninformed search methods explore the search space without prior knowledge about the goal.
Informed search algorithms, on the other hand, can do quite well given some guidance on where to look for solutions.
Informed search methods use problem-specific knowledge (heuristics) to find solutions efficiently.
uninformed search algorithms Informed search algorithms Adversarial Search (Game Search)
Uninformed (Blind) Search Strategies Informed (Heuristic) Search Strategies Used in competitive environments like
Breadth-First Search (BFS) Greedy Best-First Search games
An agent is anything that can be viewed as perceiving its environment through sensors and acting upon that
environment through effectors.
A human agent has eyes, ears, and other organs for sensors, and
hands, legs, mouth, and other body parts for effectors.
In Artificial Intelligence, an agent is any entity that perceives its environment and takes actions. A rational agent is a
specific type of agent that always aims to make the best possible decision to maximize its performance measure.
A rational agent is an intelligent entity that takes actions to maximize its performance measure based on the available
information and knowledge about its environment. Rationality in AI refers to making the best possible decision in a
given situation.
All rational agents are agents, but not all agents are rational.
As a first approximation, we will say that the right action is the one that will cause the agent to be most successful. That leaves us with the
problem of deciding how and when to evaluate the agent's success.
We use the term performance measure for the how—the criteria that determine how successful an agent is. Obviously, there is not one
fixed measure suitable for all agents.
We will insist on an objective performance measure imposed by some authority. In other words, we as outside observers establish a
standard of what it means to be successful in an environment and use it to measure the performance of agents.
As an example,
Consider the case of an agent that is supposed to vacuum a dirty floor.
1. A plausible performance measure would be the amount of dirt cleaned up in a single eight-hour shift.
2. A more sophisticated performance measure would factor in the amount of electricity consumed and the amount of noise generated as
well.
3. A third performance measure might give highest marks to an agent that not only cleans the floor quietly and efficiently, but also finds
time to go windsurfing at the weekend.
when of evaluating performance is also important. If we measured how much dirt the agent had cleaned up in the first hour of the day, we
would be rewarding those agents that start fast (even if they do little or no work later on), and punishing those that work consistently. Thus,
we want to measure performance over the long run, be it an eight-hour shift or a lifetime.
The job of AI is to design the agent program: a function that implements the agent mapping from percepts to actions. We assume this
program will run on some sort of computing device, which we will call the architecture.
Obviously, the program we choose has to be one that the architecture will accept and run. The architecture might be a plain computer, or it
might include special-purpose hardware for certain tasks, such as processing camera images or filtering audio input.
It might also include software that provides a degree of insulation between the raw computer and the agent program, so that we can
program at a higher level. In general, the architecture makes the percepts from the sensors available to the program, runs the program, and
feeds the program's action choices to the effectors as they are generated.
The relationship among agents, architectures, and programs can be summed up as follows:
Examples of agent types and their PAGE (Percept, action, goals and Environment) descriptions
"The car in front is braking"; then this triggers some established connection in the agent program to the action "initiate braking". We call
such a connection a condition-action rule written as
Even for the simple braking rule, our driver will have to maintain some sort of internal state in order to choose an action. Here, the internal
state is not too extensive—it just needs the previous frame from the camera to detect when two red lights at the edge of the vehicle go on or
off simultaneously
Along with the current state description, the agent needs some sort of goal information, which describes situations that are desirable
Utility is therefore a function that maps a state onto a real number, which describes the associated degree of happiness. A complete
specification of the utility function allows rational decisions in two kinds of cases where goals have trouble.
If an agent's sensory apparatus gives it access to the complete state of the environment, then we say that the environment is accessible to
that agent. An environment is effectively accessible if the sensors detect all aspects that are relevant to the choice of action. An accessible
environment is convenient because the agent need not maintain any internal state to keep track of the world
If the next state of the environment is completely determined by the current state and the actions selected by the agents, then we say the
environment is deterministic. In principle, an agent need not worry about uncertainty in an accessible, deterministic environment. If the
environment is inaccessible, however, then it may appear to be nondeterministic. This is particularly true if the environment is complex,
making it hard to keep track of all the inaccessible aspects. Thus, it is often better to think of an environment as deterministic or
nondeterministic/rom the point of view of the agent.
In an episodic environment, the agent's experience is divided into "episodes." Each episode consists of the agent perceiving and then
acting. The quality of its action depends just on the episode itself, because subsequent episodes do not depend on what actions occur in
previous episodes. Episodic environments are much simpler because the agent does not need to think ahead.
If the environment can change while an agent is deliberating, then we say the environment is dynamic for that agent; otherwise it is static.
Static environments are easy to deal with because the agent need not keep looking at the world while it is deciding on an action, nor need it
worry about the passage of time. If the environment does not change with the passage of time but the agent's performance score does, then
we say the environment is semidynamic.
If there are a limited number of distinct, clearly defined percepts and actions we say that the environment is discrete. Chess is
discrete—there are a fixed number of possible moves on each turn. Taxi driving is continuous—the speed and location of the taxi and the
other vehicles sweep through a range of continuous values.
Reflex agents, cannot operate well in environments for which mapping from states to actions would be too large to store and would take too
long to learn.
Goal-based agents, on the other hand, consider future actions and the desirability of their outcomes. One such kind of goal-based agent
called a problem-solving agent.
Problem-solving agents use atomic representations, that is, states of the world are considered as wholes, with no internal structure visible to
the problem solving algorithms.
Goal-based agents that use more advanced factored or structured representations are usually called planning agents.
Problems can be categorized based on their structure, complexity, and the methods required to solve them. In AI and computational
problem-solving, problems are generally classified as follows
Problem types require different problem-solving techniques. The choice depends on factors like structure, constraints, optimization needs,
and real-time requirements.
Problem formulation Example problems
Problem formulation in AI involves defining a problem in a structured way so that an agent can find a solution using search or optimization
techniques
Problem formulation is critical in AI as it determines the choice of search or optimization algorithm. Defining a clear initial state, actions,
goal, and cost function ensures efficient problem-solving.
Problem Formulation:
Initial State : Starting position (e.g., (0,0)). Traveling Salesman Problem (TSP)
Actions : Move Up, Down, Left, Right (within grid limits).
8-Puzzle Problem
State Space : All valid positions in the grid.
Robot Vacuum Cleaner Problem
Goal Test : Reaching the target position (e.g., (4,4)).
Path Cost : The number of moves taken (or distance traveled). Job Scheduling Problem
Search algorithms are one of the most important areas of Artificial Intelligence.
Based on the search problems we can classify the search algorithms into uninformed (Blind
search) search and informed search (Heuristic search) algorithms.
✔ Search: Searching is a step by step procedure to solve a search-problem in a given search space. A search problem can have three main
factors:
✔ Search Space: Search space represents a set of possible solutions, which a system may have.
✔ Start State: It is a state from where agent begins the search.
✔ Goal test: It is a function which observe the current state and returns whether the goal state is achieved or not.
✔ Search tree: A tree representation of search problem is called Search tree. The root of the search tree is the root node which is
corresponding to the initial state.
✔ Actions: It gives the description of all the available actions to the agent.
✔ Transition model: A description of what each action do, can be represented as a transition model.
✔ Path Cost: It is a function which assigns a numeric cost to each path.
✔ Solution: It is an action sequence which leads from the start node to the goal node.
✔ Optimal Solution: If a solution has the lowest cost among all solutions.
[Link]
Basic search algorithms : (Solving Problems by Searching)
Following are the four essential properties of search algorithms to compare the efficiency of these algorithms:
1. Completeness: A search algorithm is said to be complete if it guarantees to return a solution if at least any solution exists
for any random input.
2. Optimality: If a solution found for an algorithm is guaranteed to be the best solution (lowest path cost) among all other
solutions, then such a solution for is said to be an optimal solution.
3. Time Complexity: Time complexity is a measure of time for an algorithm to complete its task.
4. Space Complexity: It is the maximum storage space required at any point during the search, as the complexity of the
problem.
[Link]
Basic search algorithms : Uninformed (Blind) Search Strategies
• The uninformed search does not contain any domain knowledge such as closeness, the location of the goal.
• It operates in a brute-force way as it only includes information about how to traverse the tree and how to identify leaf and goal nodes.
• Uninformed search applies a way in which search tree is searched without any information about the search space like initial state
operators and test for the goal, so it is also called blind search.
• It can be divided into five main types:
1. Breadth-first search
2. Uniform cost search
3. Depth-first search
4. Iterative deepening depth-first search
5. Bidirectional Search
[Link]
Basic search algorithms : Uninformed (Blind) Search Strategies
Breadth-first Search
•Breadth-first search is the most common search strategy for traversing a
tree or graph. This algorithm searches breadthwise in a tree or graph, so
it is called breadth-first search.
•BFS algorithm starts searching from the root node of the tree and
expands all successor node at the current level before moving to nodes of
next level.
•The breadth-first search algorithm is an example of a general-graph
search algorithm.
•Breadth-first search implemented using FIFO queue data structure.
•BFS search algorithm traverse in layers, so it will follow the path which
is shown by the dotted arrow, and the traversed path will be:
S ABCDGH
EFIK
[Link]
Basic search algorithms : Uninformed (Blind) Search Strategies
Breadth-first Search
Advantages:
•BFS will provide a solution if any solution exists.
•If there are more than one solutions for a given problem, then BFS will
provide the minimal solution which requires the least number of steps.
Disadvantages:
•It requires lots of memory since each level of the tree must be saved into
memory to expand the next level.
•BFS needs lots of time if the solution is far away from the root node
AD
[Link]
Basic search algorithms : Uninformed (Blind) Search Strategies
Breadth-first Search
[Link]
Basic search algorithms : Uninformed (Blind) Search Strategies
Depth-first Search
In the below search tree, we have shown the flow of depth-first search,
and it will follow the order as:
Root node--->Left node ----> right node.
[Link]
Basic search algorithms : Uninformed (Blind) Search Strategies
Depth-first Search
Advantage:
•DFS requires very less memory as it only needs to store a stack of the
nodes on the path from root node to the current node.
•It takes less time to reach to the goal node than BFS algorithm (if it
traverses in the right path).
Disadvantage:
•There is the possibility that many states keep re-occurring, and there is
no guarantee of finding the solution.
•DFS algorithm goes for deep down searching and sometime it may go to
the infinite loop.
[Link]
Basic search algorithms : Uninformed (Blind) Search Strategies
Depth-first Search
[Link]
Basic search algorithms : Uninformed (Blind) Search Strategies
Depth-limited Search
[Link]
Basic search algorithms : Uninformed (Blind) Search Strategies
Depth-limited Search
Advantages:
Depth-limited search is Memory efficient.
Disadvantages:
•Depth-limited search also has a disadvantage of incompleteness.
•It may not be optimal if the problem has more than one solution.
[Link]
Basic search algorithms : Uninformed (Blind) Search Strategies
Depth-limited Search
[Link]
Basic search algorithms : Informed (Heuristic ) Search Strategies
The general approach we consider is called The choice of f determines the search strategy.
best-first search.
Most best-first algorithms include as a component of f a heuristic function, denoted
Best-first search is an instance of the general h(n):h(n) = estimated cost of the cheapest path from the state at node n to a goal state.
TREE-SEARCH or GRAPH-SEARCH Heuristic functions are the most common form in which additional knowledge of the
algorithm in which a node is selected for problem is imparted to the search algorithm
expansion based on an evaluation function, we consider them to be arbitrary, nonnegative, problem-specific functions, with one
f(n). constraint: if n is a goal node, then h(n)=0.
.
The evaluation function is construed as a cost
estimate, so the node with the lowest two ways to use heuristic information to guide search
evaluation is expanded first. The Greedy best-first search
implementation of best-first graph search is
identical to that for uniform-cost search, A* search: Minimizing the total estimated solution cost
except for the use of f instead of g to order
the priority queue.
[Link]
Basic search algorithms : Informed (Heuristic ) Search Strategies
Heuristics function: Heuristic is a function which is used in Informed Search, and it finds the most promising path. It takes the current
state of the agent as its input and produces the estimation of how close agent is from the goal. The heuristic method, however, might not
always give the best solution, but it guaranteed to find a good solution in reasonable time. Heuristic function estimates how close a state is
to the goal. It is represented by h(n), and it calculates the cost of an optimal path between the pair of states. The value of the heuristic
function is always positive.
Pure heuristic search is the simplest form of heuristic search algorithms. It expands nodes based on their heuristic value h(n).
It maintains two lists, OPEN and CLOSED list. In the CLOSED list, it places those nodes which have already expanded and in the OPEN
list, it places nodes which have yet not been expanded.
On each iteration, each node n with the lowest heuristic value is expanded and generates all its successors and n is placed to the closed
list. The algorithm continues unit a goal state is found.
[Link]
Basic search algorithms : Informed (Heuristic ) Search Strategies
Greedy best-first search algorithm always selects the path which appears best at that moment.
It is the combination of depth-first search and breadth-first search algorithms. It uses the heuristic function and search.
Best-first search allows us to take the advantages of both algorithms. With the help of best-first search, at each step, we can choose the
most promising node.
In the best first search algorithm, we expand the node which is closest to the goal node and the closest cost is estimated by heuristic
function, i.e.
f(n)= g(n).
Were, h(n)= estimated cost from node n to the goal.
The greedy best first algorithm is implemented by the priority queue.
[Link]
Basic search algorithms : Informed (Heuristic ) Search Strategies
[Link]
Basic search algorithms : Informed (Heuristic ) Search Strategies straight line distance heuristic (hsld)
Greedy best-first search
Greedy best-first search tries to expand the node that is closest to the
goal, on the grounds that this is likely to lead to a solution quickly.
Thus, it evaluates nodes by using just the heuristic function; that is, f(n)
= h(n).
Route-finding problems in Romania: we use the straight line distance
heuristic, which we will call hSLD. If the goal is Bucharest, we need to
know the straight-line distances to Bucharest, which are shown in
Figure.
For example,hSLD(In(Arad))=366. Notice that the values of hSLD
cannot be computed from the problem description itself. Moreover, it
takes a certain amount of experience to know that hSLD is correlated
with actual road distances and is, therefore, a useful heuristic.
The first node to be expanded from Arad will be Sibiu because it is closer to Bucharest than either Zerind or Timisoara.
The next node to be expanded will be Fagaras because it is closest. Fagaras in turn generates Bucharest, which is the goal.
D
70
C
150
A 36 F 17 80
B 0 G 19
C 37 H 10 A
140 E 100
D 38 I 32
120 F
E 25 J 24 80
I G 210
95
110 J 50
H
100 B
Basic search algorithms : Informed (Heuristic ) Search Strategies
The most widely known form of best-first search is called A* search (pronounced “A-star search”).
It evaluates nodes by combining g(n), the cost to reach the node, and h(n), the cost to get from the node to the goal:
f(n) = g(n) + h(n) .
Since g(n) gives the path cost from the start node to node n, and h(n) is the estimated cost of the cheapest path from n to the
goal, we have
f(n) = estimated cost of the cheapest solution through n .
A∗ search is both complete and optimal. The algorithm is identical to UNIFORM-COST-SEARCH except that A* uses g +
h instead of g.
The first condition we require for optimality is that h(n) be an admissible heuristic. An admissible heuristic is one that never overestimates
the cost to reach the goal.
Because g(n) is the actual cost to reach n along the current path, and f(n)=g(n) + h(n), we have as an immediate consequence that f(n) never
overestimates the true cost of a solution along the current path through n.
Straight-line distance hsld is admissible because the shortest path between any two points is a straight line, so the straight line cannot be an
overestimate
Second, slightly stronger condition called consistency (or sometimes monotonicity) is required only for applications of A* to graph search.
A heuristic h(n) is consistent if, for every node n and every successor n’ of n generated by any action a, the estimated cost of reaching the
goal from n is no greater than the step cost of getting to n’ plus the estimated cost of reaching the goal from n’:
h(n) ≤ c(n, a, n’) + h(n) .
Hill-climbing search
current ← MAKE-NODE(INITIAL-STATE[problem])
loop do
neighbor ← a highest valued successor of current
if VALUE [neighbor] ≤ VALUE[current] then return STATE[current]
current ← neighbor
min version will reverse inequalities and look for lowest valued successor
Hill-climbing search
Hill-climbing search
• Put n queens on an n x n board with no two queens on the same row, column, or diagonal
Hill-climbing search
Hill-climbing search
• Is this a solution?
• What is h?
Hill-climbing search
• Is this a solution?
• What is h?
Hill-climbing search
• However…
• Takes only 4 steps on average when it succeeds
• And 3 on average when it gets stuck
• (for a state space with 8^8 =~17 million states)
Hill-climbing search
• If no downhill (uphill) moves, allow sideways moves in hope that algorithm can escape
• Need to place a limit on the possible number of sideways moves to avoid infinite loops
• For 8-queens
• Now allow sideways moves with a limit of 100
• Raises percentage of problem instances solved from 14 to 94%
• However….
• 21 steps for every successful solution
• 64 for each failure
Hill-climbing search
• Stochastic hill-climbing
• Random selection among the uphill moves.
• The selection probability can vary with the steepness of the uphill move.
Hill-climbing search
When the state-space landscape has local minima, any search that moves only in the greedy
direction cannot be complete
Hill-climbing search
• Random-restart hill climbing adopts the well-known adage If at first you don’t succeed, try, try again!
• Different variations
• For each restart: run until termination vs. run for a fixed time
• Run a fixed number of restarts or run indefinitely
Simulated Annealing
A hill-climbing algorithm that never makes “downhill” moves toward states with lower value (or higher cost) is guaranteed
to be incomplete, because it can get stuck on a local maximum.
In contrast, a purely random walk—that is, moving to a successor chosen uniformly at random from the set of
successors—is complete but extremely inefficient.
Therefore, it seems reasonable to try to combine hill climbing with a random walk in some way that yields both efficiency
and completeness. Simulated annealing is such an algorithm.
In metallurgy, annealing is the process used to temper or harden metals and glass by heating them to a high temperature
and then gradually cooling them, thus allowing the material to reach a lowenergy crystalline state.
Simulated Annealing
Simulated Annealing
• A Physical Analogy:
• imagine letting a ball roll downhill on the function surface
• this is like hill-climbing (for minimization)
• now imagine shaking the surface, while the ball rolls, gradually reducing the amount of shaking
• this is like simulated annealing
• Annealing = physical process of cooling a liquid or metal until particles achieve a certain frozen crystal state
• simulated annealing:
• free variables are like particles
• seek “low energy” (high quality) configuration
• slowly reducing temp. T with particles moving around randomly
Simulated Annealing
function SIMULATED-ANNEALING( problem, schedule) return a solution state
input: problem, a problem
schedule, a mapping from time to temperature
local variables: current, a node. the amount ΔE by which the evaluation is worsened.
next, a node.
T, a “temperature” controlling the prob. of downward steps
current ← MAKE-NODE(INITIAL-STATE[problem]) • high T: probability of “locally bad” move is higher
for t ← 1 to ∞ do
T ← schedule[t] • low T: probability of “locally bad” move is lower
if T = 0 then return current • typically, T is decreased as the algorithm runs longer
next ← a randomly selected successor of current
∆E ← VALUE[next] - VALUE[current] • i.e., there is a “temperature schedule”
if ∆E > 0 then current ← next
else current ← next only with probability e∆E /T
Keeping just one node in memory might seem to be an extreme reaction to the problem of memory limitations. The local beam
search algorithm keeps track of k states rather than just one.
Genetic algorithms
• Twist on Local Search: successor is generated by combining two parent states
• A state is represented as a string over a finite alphabet (e.g. binary)
• 8-queens
• State = position of 8 queens each in a column
• Start with k randomly generated states (population)
• Evaluation function (fitness function):
• Higher values for better states.
• Opposite to heuristic function, e.g., # non-attacking pairs in 8-queens
String representation 16257483
• Produce the next generation of states by “simulated evolution”
• Random selection Can we evolve 8-queens through genetic algorithms?
• Crossover
• Random mutation
Genetic algorithms
Genetic algorithms
Genetic algorithms
Genetic algorithms
• Genetic algorithm is a variant of “stochastic beam search”
• Positive points
• Random exploration can find solutions that local search can’t
• (via crossover primarily)
• Appealing connection to human evolution
• “neural” networks, and “genetic” algorithms are metaphors!
• Negative points
• Large number of “tunable” parameters
• Difficult to replicate performance from one problem to another
• Lack of good empirical studies comparing to simpler methods
• Useful on some (small?) set of problems but no convincing evidence that GAs are better than
hill-climbing w/random restarts in general
Local search algorithms operate using a single current node (rather than multiple paths) and generally move only to
neighbors of that node. Typically, the paths followed by the search are not retained.
Although local search algorithms are not systematic, they have two key advantages:
(1) they use very little memory—usually a constant amount; and
(2) they can often find reasonable solutions in large or infinite (continuous) state spaces for which systematic
algorithms are unsuitable.
In addition to finding goals, local search algorithms are useful for solving pure optimization problems, in which the
aim is to find the best state according to an objective function.
Constraint graph
The key idea is local consistency. If we treat each variable as a node in a graph and each binary constraint as an arc, then the process of
enforcing local consistency in each part of the graph causes inconsistent values to be eliminated throughout the graph.
A single variable (corresponding to a node in the CSP network) is node-consistent if all the values
Node consistency
in the variable’s domain satisfy the variable’s unary constraints.
For example, in the variant of the Australia map-coloring problem where South Australians dislike
green, the variable SA starts with domain {red , green, blue}, and we can make it node consistent by
eliminating green, leaving SA with the reduced domain {red , blue}.
Arc consistency A variable in a CSP is arc-consistent if every value in its domain satisfies the variable’s binary
constraints. More formally, Xi is arc-consistent with respect to another variable Xj if for every value
in the current domain Di there is some value in the domain Dj that satisfies the binary constraint on
the arc (Xi,Xj).
Arc consistency
• Simplest form of propagation makes each arc consistent
• X 🡪Y is consistent iff
for every value x of X there is some allowed y
Consider the problem of scheduling the assembly of a car. The whole job is composed of tasks, and we can model each task
as a variable, where the value of each variable is the time that the task starts, expressed as an integer number of minutes.
Constraints can assert that one task must occur before another—for example, a wheel must be installed before the hubcap is
put on—and that only so many tasks can go on at once. Constraints can also specify that a task takes a certain amount of time
to complete.
The value of each variable is the time that the task starts. Next we represent precedence constraints between individual
tasks. Whenever a task T1 must occur before task T2 , and task T1 takes duration d1 to complete, we add an arithmetic
constraint of the form T1 + d1 ≤ T2 .
Precedence constraints
Suppose we have four workers to install wheels, but they have to share one tool that helps put the axle in place.
We need a disjunctive constraint to say that AxleF and AxleB must not
overlap in time; either one comes first or the other does:
(AxleF + 10 ≤ AxleB) or (AxleB + 10 ≤ AxleF ) .
We also need to assert that the inspection comes last and takes 3 minutes. For every variable except Inspect we add a
constraint of the form X +dX ≤ Inspect .
Finally, suppose there is a requirement to get the whole assembly done in 30 minutes. We can achieve that by limiting the
domain of all variables:
Di = {1, 2, 3, . . . , 27} .
• Discrete variables
• finite domains:
• n variables, domain size d 🡪 O(dn) complete assignments
• e.g., Boolean CSPs, incl. Boolean satisfiability (NP-complete)
• infinite domains:
• set of integers, strings, etc.
• e.g., job scheduling, variables are start/end days for each job
• need a constraint language, e.g., StartJob1 + 5 ≤ StartJob3
• Continuous variables
• e.g., start/end times for Hubble Space Telescope observations
• linear constraints solvable in polynomial time by LP
Varieties of constraints
Example: Cryptarithmetic
ordinary nodes
• Variables: F T U W R O X1 X2 X3
hypernodes (the squares),
• Domains: {0,1,2,3,4,5,6,7,8,9}
CONSTRAINT hypergraph ,
• Constraints: Alldiff (F,T,U,W,R,O)
• O + O = R + 10 · X1
X1 + W + W = U + 10 · X2
X2 + T + T = O + 10 · X3
• X3 = F, T ≠ 0, F ≠ 0
• Search – no adversary
• Solution is (heuristic) method for finding goal
• Heuristics and CSP techniques can find optimal solution
• Evaluation function: estimate of cost from start to goal through given node
• Examples: path planning, scheduling activities
• Games – adversary
• Solution is strategy
• strategy specifies move for every possible opponent reply.
• Time limits force an approximate solution
• Evaluation function: evaluate “goodness” of game position
• Examples: chess, checkers, Othello, backgammon
Games as Search
• Two players: MAX and MIN
• MAX moves first and they take turns until the game is over
• Winner gets reward, loser gets penalty.
• “Zero sum” means the sum of the reward and the penalty is a constant.
• Formal definition as a search problem:
• Initial state: Set-up specified by the rules, e.g., initial board configuration of chess.
• Player(s): Defines which player has the move in a state.
• Actions(s): Returns the set of legal moves in a state.
• Result(s,a): Transition model defines the result of a move.
• Successor function: list of (move,state) pairs specifying legal moves.
• Terminal-Test(s): Is the game finished? True if finished, false otherwise.
• Utility function(s,p): Gives numerical value of terminal state s for player p.
• E.g., win (+1), lose (-1), and draw (0) in tic-tac-toe.
• E.g., win (+1), lose (0), and draw (1/2) in chess.
• MAX uses search tree to determine next move.
Designed to find the optimal strategy for Max and find best move:
• Optimal?
• Yes (against an optimal opponent).
Can it be beaten by an opponent playing sub-optimally?
Properties of minimax • No.
• Time complexity?
• O(bm)
• Space complexity?
• O(bm) (depth-first search, generate all actions at once)
• O(m) (backtracking search, generate actions one at a time)
The problem with minimax search is that the number of game states it has to examine is exponential in the depth of the tree.
Unfortunately, we can’t eliminate the exponent, but it turns out we can effectively cut it in half.
The trick is that it is possible to compute the correct minimax decision without looking at every node in the game tree. That
is, we can do with the idea of pruning to eliminate large parts of the tree from consideration.
The particular technique we examine is called alpha–beta pruning. When applied to a standard minimax tree, it returns the
same move as minimax would, but prunes away branches that cannot possibly influence the final decision.
a) The first leaf below B has the value 3. Hence, B, which is a MIN node, has a value of at most 3.
b) The second leaf below B has a value of 12; MIN would avoid this move, so the value of B is still at most 3.
(c) The third leaf below B has a value of 8; we have seen all B’s successor states, so the value of B is exactly 3. Now,
we can infer that the value of the root is at least 3, because MAX has a choice worth 3 at the root.
(d) The first leaf below C has the value 2. Hence, C, which is a MIN node, has a value of at most 2. But we know that B
is worth 3, so MAX would never choose C. Therefore, there is no point in looking at the other successor states of C.
This is an example of alpha–beta pruning.
(e) The first leaf below D has the value 14, so D is worth at most 14. This is still higher than MAX’s best alternative (i.e.,
3), so we need to keep exploring D’s successor states. Notice also that we now have bounds on all of the successors of the
root, so the root’s value is also at most 14.
(f) The second successor of D is worth 5, so again we need to keep exploring. The third successor is worth 2, so now D is
worth exactly 2. MAX’s decision at the root is to move to B, giving a value of 3.
• When ?
• Prune whenever α ≥ β.
• Prune below a Max node whose alpha value becomes greater than or equal
to the beta value of its ancestors.
• Max nodes update alpha based on children’s returned values.
• Prune below a Min node whose beta value becomes less than or equal to the
alpha value of its ancestors.
• Min nodes update beta based on children’s returned values.
• Best-Case
• each player’s best move is the left-most child (i.e., evaluated first)
• in practice, performance is closer to best rather than worst-case
• E.g., sort moves by the remembered move values found last time.
Effectiveness of Alpha-Beta Search • E.g., expand captures first, then threats, then forward moves, etc.
• E.g., run Iterative Deepening search, sort by value last iteration.
5 6
3 4 1 2 7 8
Game Playing
Max
5 6
3 4 1 2 7 8
Game Playing
3 4
6 5 8 7 2 1
Game Playing
Max
3 4
6 5 8 7 2 1
Movement Planning
The effectiveness of alpha–beta pruning is highly dependent on the order in which the states are examined. For example, in Figure (e) and
(f), we could not prune any successors of D at all because the worst successors (from the point of view of MIN) were generated first.
If the third successor of D had been generated first, we would have been able to prune the other two. This suggests that it might be
worthwhile to try to examine first the successors that are likely to be best.
Adding dynamic move-ordering schemes, such as trying first the moves that were found to be best in the past, brings us quite close to the
theoretical limit. The past could be the previous move—often the same threats remain—or it could come from previous exploration of the
current move. One way to gain information from the current move is with iterative deepening search.
The best moves are often called killer moves and to try them first is called the killer move heuristic.
Intelligent agents are supposed to maximize their performance measure. Achieving this is
sometimes simplified if the agent can adopt a goal and aim at satisfying it. Let us first look at
why and how an agent might do this.
Imagine an agent in the city of Arad, Romania, enjoying a touring holiday. The agent’s
performance measure contains many factors: it wants to improve its suntan, improve its
Romanian, take in the sights, enjoy the nightlife (such as it is), avoid hangovers, and so on.
The decision problem is a complex one involving many tradeoffs and careful reading of
guidebooks. Now, suppose the agent has a nonrefundable ticket to fly out of Bucharest the
following day. In that case, it makes sense for the agent to adopt the goal of getting to
Bucharest.
Courses of action that don’t reach Bucharest on time can be rejected without further
consideration and the agent’s decision problem is greatly simplified. Goals help organize
behavior by limiting the objectives that the agent is trying to achieve and hence the actions it
needs to consider.
Goal formulation, based on the current situation and the agent’s performance measure, is the
first step in problem solving.
Let us assume that the agent will consider actions at the level of driving from one
major town to another. Each state therefore corresponds to being in a particular
town.
The successors of Sibiu are Rimnicu Vilcea and Fagaras, with costs 80 and 99, respectively
Rimnicu Vilcea, is expanded next, adding Pitesti with cost 80 + 97=177.
The least-cost node is now Fagaras, so it is expanded, adding Bucharest with cost 99+211=310.
goal node has been generated,but uniform-cost search keeps going, Pitesti to Bucharest with cost 80+97+101= 278
checks to see if this new path is better than the old one; it is, so the old one is discarded. Bucharest, now with g-cost 278