
/***************************************************************************

                                 ChessV

                   COPYRIGHT (C) 2005 BY GREGORY STRONG

This file is part of ChessV.  ChessV is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public License as 
published by the Free Software Foundation; either version 2 of the License, 
or (at your option) any later version.

ChessV is distributed in the hope that it will be useful, but WITHOUT ANY 
WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for 
more details; the file 'COPYING' contains the License text, but if for
some reason you need a copy, please write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

****************************************************************************/


#include "StdAfx.h"
#include "../../ChessV.h"
#include "../../PieceType.h"
#include "../../Piece.h"
#include "../../Direction.h"
#include "../../Rand.h"
#include "../../GameParameters.h"
#include "OpulentChessGame.h"
#include "Decimal_Types.h"

#include "Decimal_Data.h"
//	this include file contains data matricies for square bonuses,
//	outpost bonuses, etc.  it also contains some macros used here.


//	instances of the PieceTypes
DecimalCamelFerz DecimalCamelFerz::decimalCamelFerz;
DecimalKnightWazir DecimalKnightWazir::decimalKnightWazir;


Game *CreateOpulentChessGame( Board &brd, Player &plr0, Player &plr1 )
{
	return new OpulentChessGame( brd, plr0, plr1 );
}

OpulentChessGame::OpulentChessGame( Board &board, Player &whitePlayer, Player &blackPlayer ):
	Game(board, whitePlayer, blackPlayer),
	enPassant(true)
{
	// ***************************************** //
	// ***                                   *** //
	// ***  set rules and evaluation values  *** //
	// ***                                   *** //
	// ***************************************** //

	//	implement 50-move draw rule (100 half-moves)
	autoDrawPeriod = 100;

	//	turn on use of pawn structure evaluation
	usePawnStructureEvaluation = true;

	//	turn off null-move after 24 pieces have been captured
	endgameCaptureThreshold = 24;

	//	razoring and futility pruning margins
	razorMargin = 4000;
	futilityMargin = 1800;
	extendedFutilityMargin = 2400;

	// *** PHASES *** //

	//	we have to set up the phases we wish to have in this game;
	//	we will keep it simple and have 3: opening, midgame, and endgame
	nPhases = 3;

	//	settings for phase 0 (opening)
	phases[0].SetNumber( 0 );
	phases[0].SetMobilityFactor( 0 );
	phases[0].SetPawnDeficiencyFactor( 8 );
	phases[0].SetSquareValuesFactor( 1 );
	phases[0].SetKingSafetyFactor( 6 );
	phases[0].SetTropismFactor( 6 );

	//	settings for phase 1 (midgame)
	phases[1].SetNumber( 1 );
	phases[1].SetMobilityFactor( 0 );
	phases[1].SetPawnDeficiencyFactor( 10 );
	phases[1].SetSquareValuesFactor( 1 );
	phases[1].SetKingSafetyFactor( 8 );
	phases[1].SetTropismFactor( 10 );
	
	//	settings for phase 2 (endgame)
	phases[2].SetNumber( 2 );
	phases[2].SetMobilityFactor( 0 );
	phases[2].SetPawnDeficiencyFactor( 16 );
	phases[2].SetSquareValuesFactor( 1 );
	phases[2].SetKingSafetyFactor( 0 );
	phases[2].SetTropismFactor( 10 );

	// *** OUTPOSTS *** //

	//	we wish to be able to give bonuses to pieces that are 'posted'-
	//	that is, which are centrally located and cannot be reached by
	//	enemy pawns (because adjacent pawns are gone, or have advanced
	//	beyond the piece).  we also wish to be able to give different
	//	bonuses for different types of minor pieces (a posted Knight is
	//	worth more than a posted Bishop.)

	//	we will use the user variable 'gameInt1' in the PieceType class
	//	to store the 'outpost factor' for a given piece.  this value will
	//	be multiplied by the square-values stored in the 'outpost' array.
	DecimalKnightWazir::decimalKnightWazir.gameInt1 = 10;
	DecimalCamelFerz::decimalCamelFerz.gameInt1 = 10;
	DecimalLion::decimalLion.gameInt1 = 10;
	DecimalBishop::decimalBishop.gameInt1 = 7;


	// *** INITIALIZATION *** //

	//	initialize hashes
	enPassantHashMap = new HashMap( board.GetNumberOfSquares() );
	castlingHash0k = rand_32();
	castlingHash0q = rand_32();
	castlingHash1k = rand_32();
	castlingHash1q = rand_32();

	//	basic initialization
	board.Initialize( this, BITBOARD_128 );
}

void OpulentChessGame::AddPlayerPieceTypes()
{
	//	add the piece types that each player may have
	board.AddPlayerPieceTypeBothPlayers( DecimalRook::decimalRook );
	board.AddPlayerPieceTypeBothPlayers( DecimalBishop::decimalBishop );
	board.AddPlayerPieceTypeBothPlayers( DecimalKnightWazir::decimalKnightWazir );
	board.AddPlayerPieceTypeBothPlayers( DecimalQueen::decimalQueen );
	board.AddPlayerPieceTypeBothPlayers( DecimalKing::decimalKing );
	board.AddPlayerPieceTypeBothPlayers( GrandChessPawn::grandChessPawn );
	board.AddPlayerPieceTypeBothPlayers( DecimalArchbishop::decimalArchbishop );
	board.AddPlayerPieceTypeBothPlayers( DecimalChancellor::decimalChancellor );
	board.AddPlayerPieceTypeBothPlayers( DecimalCamelFerz::decimalCamelFerz );
	board.AddPlayerPieceTypeBothPlayers( DecimalLion::decimalLion );
}

void OpulentChessGame::InitializeBoard()
{
	//	add the piece types that each player may have
	AddPlayerPieceTypes();

	//	place pieces
	char *FEN = "rw6wr/clbnqknbla/ppppbbpppp/4pp4/10/10/4PP4/PPPPNNPPPP/CLBNQKNBLA/RW6WR";
	if( LookupStringParameter( "array", FEN ) )
		useOpeningBook = false;
	board.PlacePiecesByFEN( FEN );

	// *** OPENING BOOK *** //
	if( useOpeningBook )
	{
		//	select the name of the opening book for 
		//	this particular combination of armies
		Book *pBook = new Book( &board );
		board.SetOpeningBook( pBook, "openings\\OpulentChess.txt" );
	}

	LookupBoolParameter( "en-passant", enPassant );

	board.PostInitialize();
}

Piece *OpulentChessGame::AddPiece
	( PieceType &pieceType,
	  int nPlayer,
	  int nRank,
	  int nFile )
{
	Piece *newPiece = Game::AddPiece( pieceType, nPlayer, nRank, nFile );

	if( pieceType.IsPawn() )
	{
		if( newPiece->GetPlayerNumber() == 0 )
			newPiece->GetPromotionZone().AddToZone( 70, 99 );
		else
			newPiece->GetPromotionZone().AddToZone( 0, 29 );
	}

	return newPiece;
}

void OpulentChessGame::AddSpecialMoves
	( int currentPlayer, 
	  MovementList &stack, 
	  GameRec &gameRecord, 
	  bool quiescentSearch )
{
	//	check for en-passant
	if( enPassant )
		Game::AddEnPassantMoves( stack, gameRecord, quiescentSearch );
}

bool OpulentChessGame::MoveBeingMade
	( MoveInfo &moveInfo,
	  GameRec &gameRecord )
{
	// *** UPDATE gameInt1 *** //

	//	gameInt1 is a 'user' field in the game records that a game can use
	//	for any purpose.  we will use it to track the forward progress of 
	//	the game, so we can determine which Phase we are in ('opening', 
	//	'midgame', or 'endgame' in our case)

	if( gameRecord.gameInt1 < 14 )
	{
		//	we are in the opening until gameInt1 reaches 14
		//	in the opening, we increment gameInt1 for the following moves:
		//		- any capture
		//		- the first move of any piece
		//		- any pawn push to rank 5+ (code value of 4+)
		//		- in the special case of castling, add 3 to gameInt1
		if( gameRecord.materialCaptured > 0 ||
			(gameRecord.pieceMoved->GetFlags() & (FLAGS_HAS_MOVED | FLAGS_HAS_MOVED_TWICE)) == FLAGS_HAS_MOVED ||
			(gameRecord.pieceMoved->IsPawn() && 
				board.ranks[gameRecord.pieceMoved->GetPlayerNumber()][gameRecord.pieceMoved->GetSquareNumber()] >= 4) )
			gameRecord.gameInt1++;
	}

	return true;
}

Phase &OpulentChessGame::AdjustEvaluation
	( int &eval,
	  PawnHash *pPawnHash )
{
	Phase *currentPhase = phases;

	if( board.GetCurrentGameRecord().gameInt1 < 14 )
	{
		// *** The OPENING *** //

		//	in the opening we consider the following things:
		//		- give bonus for developing the knights
		//		- penalize the queen, unicorn(s), and lions for moving early
		//		- give a bonus for castling; give a penalty for losing the ability to castle
		//		- give a penalty for moving pieces twice, and a bigger penalty for moving 3 times
		//		- penalize the blocking of center pawns

		//	use this "factor" to scale down the adjustments to be applied here, 
		//	so that the adjustments become smaller and smaller as we leave the 
		//	opening and enter the mid-game
		int factor = MAX(board.GetCurrentGameRecord().gameInt1 - 4, 0);
		int factor6 = 640 - (factor << 6);	//   \ 
		int factor5 = 320 - (factor << 5);  //    \_  different adjustments
		int factor4 = 160 - (factor << 4);  //    /   from large to small
		int factor3 = 80 - (factor << 3);   //   / 

		//	give a penalty for moving major pieces (chancellor, archbishop, and queen)
		BitBoard128 majors = DecimalQueen::decimalQueen.GetPieces( 0 ) | 
			DecimalChancellor::decimalChancellor.GetPieces( 0 ) |
			DecimalArchbishop::decimalArchbishop.GetPieces( 0 );
		while( majors )
		{
			int square = majors.GetFirstBit();
			majors.ToggleBit( square );
			if( board.GetSquareContents( square )->GetFlags() & FLAGS_HAS_MOVED )
				eval -= factor6;
		}
		majors = DecimalQueen::decimalQueen.GetPieces( 1 ) | 
			DecimalChancellor::decimalChancellor.GetPieces( 1 ) |
			DecimalArchbishop::decimalArchbishop.GetPieces( 1 );
		while( majors )
		{
			int square = majors.GetFirstBit();
			majors.ToggleBit( square );
			if( board.GetSquareContents( square )->GetFlags() & FLAGS_HAS_MOVED )
				eval += factor6;
		}

		if( testingPosition )
			eval += PenalizePiecesForMovingMultipleTimes();

		// *** DON'T BLOCK CENTER PAWNS IN OPENING *** //
		if( board.GetSquareContents( 34 ) != NULL &&
			board.GetSquareContents( 24 ) != NULL &&
			!board.GetSquareContents( 24 )->HasMoved() )
			eval -= factor5;
		if( board.GetSquareContents( 35 ) != NULL &&
			board.GetSquareContents( 25 ) != NULL &&
			!board.GetSquareContents( 25 )->HasMoved() )
			eval -= factor5;
		if( board.GetSquareContents( 33 ) != NULL &&
			board.GetSquareContents( 23 ) != NULL &&
			!board.GetSquareContents( 23 )->HasMoved() )
			eval -= factor5;
		if( board.GetSquareContents( 36 ) != NULL &&
			board.GetSquareContents( 26 ) != NULL &&
			!board.GetSquareContents( 26 )->HasMoved() )
			eval -= factor5;

		if( board.GetSquareContents( 64 ) != NULL &&
			board.GetSquareContents( 74 ) != NULL &&
			!board.GetSquareContents( 74 )->HasMoved() )
			eval += factor5;
		if( board.GetSquareContents( 65 ) != NULL &&
			board.GetSquareContents( 75 ) != NULL &&
			!board.GetSquareContents( 75 )->HasMoved() )
			eval += factor5;
		if( board.GetSquareContents( 63 ) != NULL &&
			board.GetSquareContents( 73 ) != NULL &&
			!board.GetSquareContents( 73 )->HasMoved() )
			eval += factor5;
		if( board.GetSquareContents( 66 ) != NULL &&
			board.GetSquareContents( 76 ) != NULL &&
			!board.GetSquareContents( 76 )->HasMoved() )
			eval += factor5;
	}
	else if( board.GetNumberOfCapturedPieces() > 34 ||
		board.GetMaterial( 0 ) - board.GetPawnMaterial( 0 ) + 
		board.GetMaterial( 1 ) - board.GetPawnMaterial( 1 ) < 22000 )
		//	we are in the end-game
		currentPhase = phases + 2;
	else
		//	we are in the mid-game
		currentPhase = phases + 1;

	if( pPawnHash != NULL )
	{
		// *** OUTPOSTS *** //

		//	outposts are minor pieces in central squares that cannot be driven off by enemy pawns.
		//	the basic output bonus is the value of the piece's square in the 'outpost' array, times
		//	the value of the piece type's 'outpost factor' (stored in 'gameInt1'.)

		//	a posted piece that is protected by one of its own pawns is extra good, so
		//	it gets 150% of the above bonus.  a posted piece protected by two of its
		//	own pawns is really, really good, because if the posted piece is captured,
		//	the player will have a protected, passed pawn.  a posted piece that is thus
		//	protected by 2 pawns gets double the standard output bonus.

		//	loop through all minor pieces
		BitBoard128 minors;
		minors = DecimalKnightWazir::decimalKnightWazir.GetPieces( 0 ) | 
			DecimalBishop::decimalBishop.GetPieces( 0 ) |
			DecimalLion::decimalLion.GetPieces( 0 ) |
			DecimalCamelFerz::decimalCamelFerz.GetPieces( 0 );
		while( minors )
		{
			int square = minors.GetFirstBit();
			minors.ToggleBit( square );
			Piece *piece = board.GetSquareContents( square );
			if( outpost_10x10[square] > 0 && piece->GetType().gameInt1 > 0 &&
				((int) (pPawnHash->nPawnsPerFile[1][board.files[0][square]-1]) == 0 ||
				(int) (pPawnHash->backPawnRank[1][board.files[0][square]-1]) <= board.ranks[0][square]) &&
				((int) (pPawnHash->nPawnsPerFile[1][board.files[0][square]+1]) == 0 ||
				(int) (pPawnHash->backPawnRank[1][board.files[0][square]+1]) <= board.ranks[0][square]) )
			{
				//	basic bonus for player 0's posted piece
				eval += outpost_10x10[square] * piece->GetType().gameInt1;
				int pawnSquare1 = board.GetMovementMatrix( DIRECTION_SE )[square];
				int pawnSquare2 = board.GetMovementMatrix( DIRECTION_SW )[square];
				if( board.GetSquareContents( pawnSquare1 ) != NULL &&
					board.GetSquareContents( pawnSquare1 )->GetPlayerNumber() == 0 && 
					board.GetSquareContents( pawnSquare1 )->GetType().IsPawn() )
					//	additional 50% bonus for this pawn defender
					eval += (outpost_10x10[square] * piece->GetType().gameInt1) >> 1;
				if( board.GetSquareContents( pawnSquare2 ) != NULL &&
					board.GetSquareContents( pawnSquare2 )->GetPlayerNumber() == 0 && 
					board.GetSquareContents( pawnSquare2 )->GetType().IsPawn() )
					//	additional 50% bonus for this pawn defender
					eval += (outpost_10x10[square] * piece->GetType().gameInt1) >> 1;
			}
		}
		minors = DecimalKnightWazir::decimalKnightWazir.GetPieces( 1 ) | 
			DecimalBishop::decimalBishop.GetPieces( 1 ) |
			DecimalLion::decimalLion.GetPieces( 1 ) |
			DecimalCamelFerz::decimalCamelFerz.GetPieces( 1 );
		while( minors )
		{
			int square = minors.GetFirstBit();
			minors.ToggleBit( square );
			Piece *piece = board.GetSquareContents( square );
			if( outpost_10x10[board.flipSquare[1][square]] > 0 && piece->GetType().gameInt1 > 0 &&
				((int) (pPawnHash->nPawnsPerFile[0][board.files[0][square]-1]) == 0 ||
				(int) (pPawnHash->backPawnRank[0][board.files[0][square]-1]) <= board.ranks[0][square]) &&
				((int) (pPawnHash->nPawnsPerFile[0][board.files[0][square]+1]) == 0 ||
				(int) (pPawnHash->backPawnRank[0][board.files[0][square]+1]) <= board.ranks[0][square]) )
			{
				//	basic bonus for player 1's posted piece
				eval -= outpost_10x10[square] * piece->GetType().gameInt1;
				int pawnSquare1 = board.GetMovementMatrix( DIRECTION_SE )[square];
				int pawnSquare2 = board.GetMovementMatrix( DIRECTION_SW )[square];
				if( board.GetSquareContents( pawnSquare1 ) != NULL && 
					board.GetSquareContents( pawnSquare1 )->GetPlayerNumber() == 1 && 
					board.GetSquareContents( pawnSquare1 )->GetType().IsPawn() )
					//	additional 50% bonus for this pawn defender
					eval -= (outpost_10x10[board.flipSquare[1][square]] * piece->GetType().gameInt1) >> 1;
				if( board.GetSquareContents( pawnSquare2 ) != NULL &&
					board.GetSquareContents( pawnSquare2 )->GetPlayerNumber() == 1 && 
					board.GetSquareContents( pawnSquare2 )->GetType().IsPawn() )
					//	additional 50% bonus for this pawn defender
					eval -= (outpost_10x10[board.flipSquare[1][square]] * piece->GetType().gameInt1) >> 1;
			}
		}

		// *** ROOK and CHANCELLOR on OPEN and SEMI-OPEN FILE BONUS *** //
		BitBoard128 rooks;
		rooks = DecimalRook::decimalRook.GetPieces( 0 ) | 
			DecimalChancellor::decimalChancellor.GetPieces( 0 );
		while( rooks )
		{
			int square = rooks.GetFirstBit();
			rooks.ToggleBit( square );
			if( pPawnHash->nPawnsPerFile[0][board.files[0][square]] == 0 )
			{
				//	file at least semi-open
				eval += 50;
				if( pPawnHash->nPawnsPerFile[1][board.files[0][square]] == 0 )
					//	fully open file
					eval += 20;
			}
		}
		rooks = DecimalRook::decimalRook.GetPieces( 1 ) | 
			DecimalChancellor::decimalChancellor.GetPieces( 1 );
		while( rooks )
		{
			int square = rooks.GetFirstBit();
			rooks.ToggleBit( square );
			if( pPawnHash->nPawnsPerFile[1][board.files[0][square]] == 0 )
			{
				//	file at least semi-open
				eval -= 50;
				if( pPawnHash->nPawnsPerFile[0][board.files[0][square]] == 0 )
					//	fully open file
					eval -= 20;
			}
		}
	}

	//	TWO-BISHOPS BONUS
	//	give bonus for having both bishops
	//		TODO: temporarily removed

	return *currentPhase;
}

int OpulentChessGame::EnumeratePromotions
	( Piece *piece, 
	  int fromSquare,
	  int toSquare,
	  Piece **pieces )
{
	int count = 0;

	//	in Opulent Chess, we may only promote to the type of a friendly 
	//	piece that has been captured (for which it is exchanged.)
	
	if( toSquare >= 10 && toSquare < 90 )
		//	promotion is optional, so push "exchange" to same piece
		pieces[count++] = piece;

	bool rookFound = false;
	bool knightFound = false;
	bool bishopFound = false;
	bool queenFound = false;
	bool chancellorFound = false;
	bool archbishopFound = false;
	bool lionFound = false;
	bool wizardFound = false;

	for( int x = 0; x < board.GetNumberOfPieces( piece->GetPlayerNumber() ); x++ )
	{
		Piece *currentPiece = board.GetPiece( piece->GetPlayerNumber(), x );
		if( currentPiece->IsCaptured() )
		{
			if( currentPiece->GetType() == DecimalRook::decimalRook && !rookFound )
			{
				rookFound = true;
				pieces[count++] = currentPiece;
			}
			else if( currentPiece->GetType() == DecimalKnightWazir::decimalKnightWazir && !knightFound )
			{
				knightFound = true;
				pieces[count++] = currentPiece;
			}
			else if( currentPiece->GetType() == DecimalBishop::decimalBishop && !bishopFound )
			{
				bishopFound = true;
				pieces[count++] = currentPiece;
			}
			else if( currentPiece->GetType() == DecimalQueen::decimalQueen && !queenFound )
			{
				queenFound = true;
				pieces[count++] = currentPiece;
			}
			else if( currentPiece->GetType() == DecimalArchbishop::decimalArchbishop && !archbishopFound )
			{
				archbishopFound = true;
				pieces[count++] = currentPiece;
			}
			else if( currentPiece->GetType() == DecimalChancellor::decimalChancellor && !chancellorFound )
			{
				chancellorFound = true;
				pieces[count++] = currentPiece;
			}
			else if( currentPiece->GetType() == DecimalLion::decimalLion && !lionFound )
			{
				lionFound = true;
				pieces[count++] = currentPiece;
			}
			else if( currentPiece->GetType() == DecimalCamelFerz::decimalCamelFerz && !wizardFound )
			{
				wizardFound = true;
				pieces[count++] = currentPiece;
			}
		}
	}

	return count;
}

word32 OpulentChessGame::AdjustPrimaryHash
	( word32 primaryHash )
{
	if( enPassant )
		return primaryHash ^ GetEnPassantHash( board.GetCurrentGameRecord(), enPassantHashMap );
	return primaryHash;
}


void OpulentChessGame::AboutToStartThinking
	( int currentPlayer )
{
	board.ClearTranspositionTable();
	if( currentPlayer == 0 )
	{
		DecimalKnightWazir::decimalKnightWazir.SetBaseValue( 4200 );
		DecimalBishop::decimalBishop.SetBaseValue( 3700 );
	}
	else
	{
		DecimalKnightWazir::decimalKnightWazir.SetBaseValue( 4000 );
		DecimalBishop::decimalBishop.SetBaseValue( 3950 );
	}
}
