How to do it...

We will create the base class for handling all of our main algorithms and implement the Minimax function as follows:

  1. Create the BoardAI class:
using UnityEngine; 
using System.Collections; 
 
public class BoardAI 
{ 
 
} 
  1. Declare the Minimax function:
public static float Minimax( 
        Board board, 
        int player, 
        int maxDepth, 
        int currentDepth, 
        ref Move bestMove) 
{ 
    // next steps here 
} 
  1. Consider the base case:
if (board.IsGameOver() || currentDepth == maxDepth) 
    return board.Evaluate(player); 
  1. Set the initial values depending on the player:
bestMove = null; 
float bestScore = Mathf.Infinity; 
if (board.GetCurrentPlayer() == player) 
    bestScore = Mathf.NegativeInfinity; 
  1. Loop through all the possible moves and return the best score:

Get Unity 2018 Artificial Intelligence Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.