///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//         This example code is from the book:
//
//           Object-Oriented Programming with C++ and OSF/Motif
//         by
//           Douglas Young
//           Prentice Hall, 1992
//           ISBN 0-13-630252-1	
//
//         Copyright 1991 by Prentice Hall
//         All Rights Reserved
//
//  Permission to use, copy, modify, and distribute this software for 
//  any purpose except publication and without fee is hereby granted, provided 
//  that the above copyright notice appear in all copies of the software.
///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////
// MoveGenerator.C
//////////////////////////////////////////////////////
#include "MoveGenerator.h"
#include "Board.h"
#include "unistd.h"
#include "math.h"

#define CENTER 4

MoveGenerator::MoveGenerator()
{
    srand48 ( ( long ) getpid() );
}

// A smarter move generator function that uses a one-move look-ahead
// to choose moves. Algorithm is:
//
//     If the game can win in one move, it does so.
//     Else If the user can win in one move, block the move
//     Else If the center square is open, grab it
//     Else pick a random move from those available

int MoveGenerator::getNextMove ( Board *board )
{
    int randomIndex, movesLeft, nextMove;
    
    // Get the list of free squares on the Board
    
    int * const freeSquares = board->freeSquares ( movesLeft );

    // If center is free, grab it.

    if ( movesLeft == 0 )
	return -1;

    // See if we can win with this move

    if( ( nextMove = board->winningMove ( OO ) ) > 0 )
	return nextMove;

    // Check if user is about to win

    if( ( nextMove = board->winningMove ( XX ) ) > 0 )
	return nextMove;

    // Grab the middle 

    if( board->value ( CENTER ) == NOBODYYET )
	return CENTER;
    
    // Pick one of the free squares at random and return it
    
    randomIndex = ( int ) ( movesLeft * drand48() );
    
    return freeSquares[randomIndex];
}
