Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Game Theory
  • Game Theory in DSA
  • Nash Equilibrium
  • Normal form games
  • Minimax Algorithm
  • Impartial games
  • Combinatorial Game Theory
  • Nim Game
  • Grundy Numbers
  • Sprague Grundy Theorem
  • Minimax Algo
  • Alpha Beta Pruning
  • Zorbist Hashing
  • Coin Game
  • DP in Game Theory
  • Problems on Game Theory for CP
Open In App
Next Article:
Finding optimal move in Tic-Tac-Toe using Minimax Algorithm in Game Theory
Next article icon

Introduction to Evaluation Function of Minimax Algorithm in Game Theory

Last Updated : 20 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: Minimax Algorithm in Game Theory
As seen in the above article, each leaf node had a value associated with it. We had stored this value in an array. But in the real world when we are creating a program to play Tic-Tac-Toe, Chess, Backgammon, etc. we need to implement a function that calculates the value of the board depending on the placement of pieces on the board. This function is often known as Evaluation Function. It is sometimes also called a Heuristic Function.
The evaluation function is unique for every type of game. In this post, the evaluation function for the game Tic-Tac-Toe is discussed. The basic idea behind the evaluation function is to give a high value for a board if the maximizer turn or a low value for the board if the minimizer turn.
For this scenario let us consider X as the maximizer and O as the minimizer.
Let us build our evaluation function : 

  • If X wins on the board we give it a positive value of +10. 
     

evaluation_function1

  • If O wins on the board we give it a negative value of -10. 
     

evaluation_function2

  • If no one has won or the game results in a draw then we give a value of +0. 
     

evaluation_function3

We could have chosen any positive/negative. For the sake of simplicity, we chose 10 and shall use lowercase ‘x’ and lowercase ‘o’ to represent the players and an underscore ‘_’ to represent a blank space on the board. 
If we represent our board as a 3×3 2D character matrix, like char board[3][3]; then we have to check each row, each column, and the diagonals to check if either of the players has gotten 3 in a row.

C++




// C++ program to compute evaluation function for
// Tic Tac Toe Game.
#include<stdio.h>
#include<algorithm>
using namespace std;
 
// Returns a value based on who is winning
// b[3][3] is the Tic-Tac-Toe board
int evaluate(char b[3][3])
{
    // Checking for Rows for X or O victory.
    for (int row = 0; row<3; row++)
    {
        if (b[row][0]==b[row][1] && b[row][1]==b[row][2])
        {
            if (b[row][0]=='x')
               return +10;
            else if (b[row][0]=='o')
               return -10;
        }
    }
 
    // Checking for Columns for X or O victory.
    for (int col = 0; col<3; col++)
    {
        if (b[0][col]==b[1][col] && b[1][col]==b[2][col])
        {
            if (b[0][col]=='x')
                return +10;
            else if (b[0][col]=='o')
                return -10;
        }
    }
 
    // Checking for Diagonals for X or O victory.
    if (b[0][0]==b[1][1] && b[1][1]==b[2][2])
    {
        if (b[0][0]=='x')
            return +10;
        else if (b[0][0]=='o')
            return -10;
    }
    if (b[0][2]==b[1][1] && b[1][1]==b[2][0])
    {
        if (b[0][2]=='x')
            return +10;
        else if (b[0][2]=='o')
            return -10;
    }
 
    // Else if none of them have won then return 0
    return 0;
}
 
// Driver code
int main()
{
    char board[3][3] =
    {
        { 'x', '_', 'o'},
        { '_', 'x', 'o'},
        { '_', '_', 'x'}
    };
 
    int value = evaluate(board);
    printf("The value of this board is %d\n", value);
    return 0;
}
 
 

Java




// Java program to compute evaluation function for
// Tic Tac Toe Game.
 
class GFG
{
 
// Returns a value based on who is winning
// b[3][3] is the Tic-Tac-Toe board
static int evaluate(char b[][])
{
    // Checking for Rows for X or O victory.
    for (int row = 0; row < 3; row++)
    {
        if (b[row][0] == b[row][1] && b[row][1] == b[row][2])
        {
            if (b[row][0] == 'x')
            return +10;
            else if (b[row][0] == 'o')
            return -10;
        }
    }
 
    // Checking for Columns for X or O victory.
    for (int col = 0; col < 3; col++)
    {
        if (b[0][col] == b[1][col] && b[1][col] == b[2][col])
        {
            if (b[0][col] == 'x')
                return +10;
            else if (b[0][col] == 'o')
                return -10;
        }
    }
 
    // Checking for Diagonals for X or O victory.
    if (b[0][0] == b[1][1] && b[1][1] == b[2][2])
    {
        if (b[0][0] == 'x')
            return +10;
        else if (b[0][0] == 'o')
            return -10;
    }
    if (b[0][2] == b[1][1] && b[1][1] == b[2][0])
    {
        if (b[0][2] == 'x')
            return +10;
        else if (b[0][2] == 'o')
            return -10;
    }
 
    // Else if none of them have won then return 0
    return 0;
}
 
// Driver code
public static void main(String[] args)
{
    char board[][] =
    {
        { 'x', '_', 'o'},
        { '_', 'x', 'o'},
        { '_', '_', 'x'}
    };
 
    int value = evaluate(board);
    System.out.printf("The value of this board is %d\n", value);
}
}
 
// This code is contributed by PrinciRaj1992
 
 

Python3




# Python3 program to compute evaluation
# function for Tic Tac Toe Game.
 
# Returns a value based on who is winning
# b[3][3] is the Tic-Tac-Toe board
def evaluate(b):
  
    # Checking for Rows for X or O victory.
    for row in range(0, 3):
      
        if b[row][0] == b[row][1] and b[row][1] == b[row][2]:
          
            if b[row][0] == 'x':
                return 10
            else if b[row][0] == 'o':
                return -10
 
    # Checking for Columns for X or O victory.
    for col in range(0, 3):
      
        if b[0][col] == b[1][col] and b[1][col] == b[2][col]:
          
            if b[0][col]=='x':
                return 10
            else if b[0][col] == 'o':
                return -10
 
    # Checking for Diagonals for X or O victory.
    if b[0][0] == b[1][1] and b[1][1] == b[2][2]:
      
        if b[0][0] == 'x':
            return 10
        else if b[0][0] == 'o':
            return -10
      
    if b[0][2] == b[1][1] and b[1][1] == b[2][0]:
      
        if b[0][2] == 'x':
            return 10
        else if b[0][2] == 'o':
            return -10
      
    # Else if none of them have won then return 0
    return 0
  
# Driver code
if __name__ == "__main__":
  
    board = [['x', '_', 'o'],
             ['_', 'x', 'o'],
             ['_', '_', 'x']]
      
    value = evaluate(board)
    print("The value of this board is", value)
 
# This code is contributed by Rituraj Jain
 
 

C#




// C# program to compute evaluation function for
// Tic Tac Toe Game.
using System;
 
class GFG
{
 
// Returns a value based on who is winning
// b[3,3] is the Tic-Tac-Toe board
static int evaluate(char [,]b)
{
    // Checking for Rows for X or O victory.
    for (int row = 0; row < 3; row++)
    {
        if (b[row, 0] == b[row, 1] && b[row, 1] == b[row, 2])
        {
            if (b[row, 0] == 'x')
            return +10;
            else if (b[row, 0] == 'o')
            return -10;
        }
    }
 
    // Checking for Columns for X or O victory.
    for (int col = 0; col < 3; col++)
    {
        if (b[0, col] == b[1, col] && b[1, col] == b[2, col])
        {
            if (b[0, col] == 'x')
                return +10;
            else if (b[0, col] == 'o')
                return -10;
        }
    }
 
    // Checking for Diagonals for X or O victory.
    if (b[0, 0] == b[1, 1] && b[1, 1] == b[2, 2])
    {
        if (b[0, 0] == 'x')
            return +10;
        else if (b[0, 0] == 'o')
            return -10;
    }
    if (b[0, 2] == b[1, 1] && b[1, 1] == b[2, 0])
    {
        if (b[0, 2] == 'x')
            return +10;
        else if (b[0, 2] == 'o')
            return -10;
    }
 
    // Else if none of them have won then return 0
    return 0;
}
 
// Driver code
public static void Main(String[] args)
{
    char [,]board =
    {
        { 'x', '_', 'o'},
        { '_', 'x', 'o'},
        { '_', '_', 'x'}
    };
 
    int value = evaluate(board);
    Console.Write("The value of this board is {0}\n", value);
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
// Javascript program to compute evaluation function for
// Tic Tac Toe Game.
 
// Returns a value based on who is winning
// b[3][3] is the Tic-Tac-Toe board
function evaluate(b)
{
 
    // Checking for Rows for X or O victory.
    for (let row = 0; row < 3; row++)
    {
        if (b[row][0] == b[row][1] && b[row][1] == b[row][2])
        {
            if (b[row][0] == 'x')
                return +10;
            else if (b[row][0] == 'o')
                return -10;
        }
    }
   
    // Checking for Columns for X or O victory.
    for (let col = 0; col < 3; col++)
    {
        if (b[0][col] == b[1][col] && b[1][col] == b[2][col])
        {
            if (b[0][col] == 'x')
                return +10;
            else if (b[0][col] == 'o')
                return -10;
        }
    }
   
    // Checking for Diagonals for X or O victory.
    if (b[0][0] == b[1][1] && b[1][1] == b[2][2])
    {
        if (b[0][0] == 'x')
            return +10;
        else if (b[0][0] == 'o')
            return -10;
    }
    if (b[0][2] == b[1][1] && b[1][1] == b[2][0])
    {
        if (b[0][2] == 'x')
            return +10;
        else if (b[0][2] == 'o')
            return -10;
    }
   
    // Else if none of them have won then return 0
    return 0;
}
 
// Driver code
let board=[[ 'x', '_', 'o'],
        [ '_', 'x', 'o'],
        [ '_', '_', 'x']];
 
let value = evaluate(board);
document.write("The value of this board is "+ value+"<br>");
 
// This code is contributed by avanitrachhadiya2155
</script>
 
 
Output
The value of this board is 10

Time Complexity: O(max(row,col))
Auxiliary Space: O(1)

The idea of this article is to understand how to write a simple evaluation function for the game Tic-Tac-Toe. In the next article we shall see how to combine this evaluation function with the minimax function. Stay Tuned.
This article is written by Akshay L. Aradhya. 



Next Article
Finding optimal move in Tic-Tac-Toe using Minimax Algorithm in Game Theory
author
kartik
Improve
Article Tags :
  • DSA
  • Game Theory
Practice Tags :
  • Game Theory

Similar Reads

  • Minimax Algorithm in Game Theory | Set 1 (Introduction)
    Minimax is a kind of backtracking algorithm that is used in decision making and game theory to find the optimal move for a player, assuming that your opponent also plays optimally. It is widely used in two player turn-based games such as Tic-Tac-Toe, Backgammon, Mancala, Chess, etc.In Minimax the tw
    9 min read
  • Finding optimal move in Tic-Tac-Toe using Minimax Algorithm in Game Theory
    Prerequisites: Minimax Algorithm in Game Theory, Evaluation Function in Game TheoryLet us combine what we have learnt so far about minimax and evaluation function to write a proper Tic-Tac-Toe AI (Artificial Intelligence) that plays a perfect game. This AI will consider all possible scenarios and ma
    15+ min read
  • Minimax Algorithm in Game Theory | Set 4 (Alpha-Beta Pruning)
    Prerequisites: Minimax Algorithm in Game Theory, Evaluation Function in Game TheoryAlpha-Beta pruning is not actually a new algorithm, but rather an optimization technique for the minimax algorithm. It reduces the computation time by a huge factor. This allows us to search much faster and even go in
    11 min read
  • Minimax Algorithm in Game Theory | Set 5 (Zobrist Hashing)
    Previous posts on this topic : Minimax Algorithm in Game Theory, Evaluation Function in Game Theory, Tic-Tac-Toe AI – Finding optimal move, Alpha-Beta Pruning.Zobrist Hashing is a hashing function that is widely used in 2 player board games. It is the most common hashing function used in transpositi
    12 min read
  • Game Theory (Normal - form game) | Set 1 (Introduction)
    Game theory is a mathematical model used for decision making. It has applications in all fields of social science, as well as in logic and computer science. Game theory has come to play an increasingly important role in logic and in computer science. To be fully defined, a game must specify the foll
    4 min read
  • Pareto Optimality and its application in Game Theory
    Prerequisites: Game Theory When the strategies from game theory are discussed, they are often mentioned from a player's perspective. However, when the strategies are formed from an observer's angle whose main motive is to wish for the best outcome for every player; that is, when strategies are forme
    5 min read
  • Hungarian Algorithm for Assignment Problem (Introduction and Implementation)
    You are the head of a company with n agents and n tasks. Every agent incurs a different cost to complete each task, as given by the cost[][] matrix, where cost[i][j] represents the cost for the ith agent to perform the jth task. Your objective is to assign exactly one agent to each task—and one task
    15+ min read
  • Combinatorial Game Theory | Set 1 (Introduction)
    Combinatorial games are two-person games with perfect information and no chance moves (no randomization like coin toss is involved that can effect the game). These games have a win-or-lose or tie outcome and determined by a set of positions, including an initial position, and the player whose turn i
    3 min read
  • Expectimax Algorithm in Game Theory
    The Expectimax search algorithm is a game theory algorithm used to maximize the expected utility. It is a variation of the Minimax algorithm. While Minimax assumes that the adversary(the minimizer) plays optimally, the Expectimax doesn't. This is useful for modelling environments where adversary age
    8 min read
  • Introduction to Branch and Bound - Data Structures and Algorithms Tutorial
    Branch and bound algorithms are used to find the optimal solution for combinatory, discrete, and general mathematical optimization problems. A branch and bound algorithm provide an optimal solution to an NP-Hard problem by exploring the entire search space. Through the exploration of the entire sear
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences