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

                                 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 "../../Boards/BoardWithHangingSquares.h"
#include "CitadelChessGame.h"
#include "Historic_Chess_Types.h"


#include "../10x10/Decimal_Data.h"
//	these include files contains data matricies for square bonuses,
//	outpost bonuses, etc.  it also contains some macros used here.


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


CitadelChessGame::CitadelChessGame( Board &board, Player &whitePlayer, Player &blackPlayer ):
	Game(board, whitePlayer, blackPlayer)
{
	// ***************************************** //
	// ***                                   *** //
	// ***  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 30 pieces have been captured
	endgameCaptureThreshold = 28;

	//	razoring and futility pruning margins
	razorMargin = 6500;
	futilityMargin = 3500;
	extendedFutilityMargin = 5000;

	// *** 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( 1 );
	phases[0].SetPawnDeficiencyFactor( 8 );
	phases[0].SetSquareValuesFactor( 1 );
	phases[0].SetKingSafetyFactor( 1 );
	phases[0].SetTropismFactor( 6 );

	//	settings for phase 1 (midgame)
	phases[1].SetNumber( 1 );
	phases[1].SetMobilityFactor( 1 );
	phases[1].SetPawnDeficiencyFactor( 10 );
	phases[1].SetSquareValuesFactor( 1 );
	phases[1].SetKingSafetyFactor( 4 );
	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.
	HistoricKnight::historicKnight.gameInt1 = 10;
	HistoricBishop::historicBishop.gameInt1 = 6;
	HistoricDecurion::historicDecurion.gameInt1 = 10;
	HistoricFerz::historicFerz.gameInt1 = 2;
	
	// *** SQUARE BONUS TABLES *** //

	//	set the square-bonus tables for the piece types that we have special tables for
	HistoricPawn::historicPawn.SetSquareBonuses( 0, openingPawnSquareBonuses_10x10 );
	HistoricPawn::historicPawn.SetSquareBonuses( 1, pawnSquareBonuses_10x10 );
	HistoricPawn::historicPawn.SetSquareBonuses( 2, pawnSquareBonuses_10x10 );
	HistoricRook::historicRook.SetSquareBonuses( 0, rookSquareBonuses_10x10 );
	HistoricRook::historicRook.SetSquareBonuses( 1, rookSquareBonuses_10x10 );
	HistoricRook::historicRook.SetSquareBonuses( 2, rookSquareBonuses_10x10 );
	HistoricKnight::historicKnight.SetSquareBonuses( 0, knightSquareBonuses_10x10 );
	HistoricKnight::historicKnight.SetSquareBonuses( 1, knightSquareBonuses_10x10 );
	HistoricKnight::historicKnight.SetSquareBonuses( 2, knightSquareBonuses_10x10 );
	HistoricBishop::historicBishop.SetSquareBonuses( 0, bishopSquareBonuses_10x10 );
	HistoricBishop::historicBishop.SetSquareBonuses( 1, bishopSquareBonuses_10x10 );
	HistoricBishop::historicBishop.SetSquareBonuses( 2, bishopSquareBonuses_10x10 );
	HistoricFerz::historicFerz.SetSquareBonuses( 0, queenSquareBonuses_10x10 );
	HistoricFerz::historicFerz.SetSquareBonuses( 1, queenSquareBonuses_10x10 );
	HistoricFerz::historicFerz.SetSquareBonuses( 2, queenSquareBonuses_10x10 );
	HistoricKing::historicKing.SetSquareBonuses( 0, kingSquareBonuses_10x10 );
	HistoricKing::historicKing.SetSquareBonuses( 1, kingSquareBonuses_10x10 );
	HistoricKing::historicKing.SetSquareBonuses( 2, endgameKingSquareBonuses_10x10 );


	// *** INITIALIZATION *** //

	board.Initialize( this, BITBOARD_128 );
	InitializeBoard();
}

void CitadelChessGame::InitializeBoard()
{
	//	make the border wider to encompass the hanging squares
	board.SetBorderWidth( 60 );

	//	clear out all piece references
	for( int player = 0; player < 2; player++ )
	{
		for( int x = 0; x < 2; x++ )
		{
			rooks[player][x] = NULL;
			knights[player][x] = NULL;
			bishops[player][x] = NULL;
			elephants[player][x] = NULL;
		}
	}

	//	change names appropriately
	HistoricBishop::historicBishop.SetBitmapFileName( PIECE_SET_OLD_WORLD, 0, "images\\old_world\\WBishop.bmp" );
	HistoricBishop::historicBishop.SetBitmapFileName( PIECE_SET_OLD_WORLD, 1, "images\\old_world\\BBishop.bmp" );
	HistoricBishop::historicBishop.SetFullName( "Dabbabah" );
	HistoricBishop::historicBishop.SetNotation( "D" );

	//	add the pawns
	for( int i = 0; i < 10; i++ )
	{
		AddPiece( HistoricPawn::historicPawn, 0, 1, i );
		AddPiece( HistoricPawn::historicPawn, 1, 8, i );
	}
	//	white's pieces 
	AddPiece( HistoricRook::historicRook, 0, 0, 0 );
	AddPiece( HistoricRook::historicRook, 0, 0, 9 );
	AddPiece( HistoricKnight::historicKnight, 0, 0, 1 );
	AddPiece( HistoricKnight::historicKnight, 0, 0, 8 );
	AddPiece( HistoricElephant::historicElephant, 0, 0, 2 );
	AddPiece( HistoricElephant::historicElephant, 0, 0, 7 );
	AddPiece( HistoricBishop::historicBishop, 0, 0, 3 );
	AddPiece( HistoricBishop::historicBishop, 0, 0, 6 );
	AddPiece( HistoricFerz::historicFerz, 0, 0, 5 );
	AddPiece( HistoricKing::historicKing, 0, 0, 4 );
	//	black's pieces 
	AddPiece( HistoricRook::historicRook, 1, 9, 0 );
	AddPiece( HistoricRook::historicRook, 1, 9, 9 );
	AddPiece( HistoricKnight::historicKnight, 1, 9, 1 );
	AddPiece( HistoricKnight::historicKnight, 1, 9, 8 );
	AddPiece( HistoricElephant::historicElephant, 1, 9, 2 );
	AddPiece( HistoricElephant::historicElephant, 1, 9, 7 );
	AddPiece( HistoricBishop::historicBishop, 1, 9, 3 );
	AddPiece( HistoricBishop::historicBishop, 1, 9, 6 );
	AddPiece( HistoricFerz::historicFerz, 1, 9, 5 );
	AddPiece( HistoricKing::historicKing, 1, 9, 4 );
	//	opening book
	if( useOpeningBook )
	{
		Book *pBook = new Book( &board );
		board.SetOpeningBook( pBook, "openings\\CitadelChess.txt" );
	}

	//	add hanging squares
	BoardWithHangingSquares &myBoard = static_cast<BoardWithHangingSquares &>(board);
	myBoard.AddHangingSquare( 10, -1 );
	myBoard.AddHangingSquare( 10, 10 );
	myBoard.AddHangingSquare( -1, -1 );
	myBoard.AddHangingSquare( -1, 10 );

	board.PostInitialize();
}

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

	if( pieceType == HistoricRook::historicRook )
	{
		AddPieceToSet( newPiece, rooks, 2 );
	}
	else if( pieceType == HistoricBishop::historicBishop )
	{
		AddPieceToSet( newPiece, bishops, 2 );
	}
	else if( pieceType == HistoricElephant::historicElephant )
	{
		AddPieceToSet( newPiece, elephants, 2 );
	}
	else if( pieceType == HistoricKnight::historicKnight )
	{
		AddPieceToSet( newPiece, knights, 2 );
	}

	return newPiece;
}

void CitadelChessGame::DeletePiece
	( Piece *piece )
{
	RemovePieceFromSet( piece, knights, 2 );
	RemovePieceFromSet( piece, bishops, 2 );
	RemovePieceFromSet( piece, elephants, 2 );
	RemovePieceFromSet( piece, rooks, 2 );
}

PieceType **CitadelChessGame::GetPieceTypesRequired
	( int &nPieceTypes )
{
	nPieceTypes = board.GetPieceTypeCount();
	return( board.GetPieceTypes() );
}

bool CitadelChessGame::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 < 20 )
	{
		//	we are in the opening until gameInt1 reaches 20;
		//	in the opening, we increment gameInt1 for the following moves:
		//		- any capture
		//		- the first move of any piece
		//		- any pawn push
		//		- king's leap adds 2
		//		- castling adds 3
		if( gameRecord.materialCaptured > 0 ||
			(gameRecord.pieceMoved->GetFlags() & (FLAGS_HAS_MOVED | FLAGS_HAS_MOVED_TWICE)) == FLAGS_HAS_MOVED ||
			gameRecord.pieceMoved->IsPawn() )
			gameRecord.gameInt1++;
		else if( gameRecord.moveType == Castling )
			gameRecord.gameInt1 += 3;
		else if( gameRecord.moveType == UserMove1 )
			gameRecord.gameInt1 += 2;
	}

	return true;
}

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

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

		//	in the opening we consider the following things:
		//		- give bonus for developing minor pieces
		//		- give a penalty for moving pieces twice

		//	penalize undeveloped minor pieces
		if( knights[0][0] != NULL && !knights[0][0]->HasMoved() )
			eval -= 50;
		if( knights[0][1] != NULL && !knights[0][1]->HasMoved() )
			eval -= 50;
		if( bishops[0][0] != NULL && !bishops[0][0]->HasMoved() )
			eval -= 35;
		if( bishops[0][1] != NULL && !bishops[0][1]->HasMoved() )
			eval -= 35;
		if( elephants[0][0] != NULL && !elephants[0][0]->HasMoved() )
			eval -= 40;
		if( elephants[0][1] != NULL && !elephants[0][1]->HasMoved() )
			eval -= 40;
		if( knights[1][0] != NULL && !knights[0][0]->HasMoved() )
			eval += 50;
		if( knights[1][1] != NULL && !knights[0][1]->HasMoved() )
			eval += 50;
		if( bishops[1][0] != NULL && !bishops[0][0]->HasMoved() )
			eval += 35;
		if( bishops[1][1] != NULL && !bishops[0][1]->HasMoved() )
			eval += 35;
		if( elephants[1][0] != NULL && !elephants[0][0]->HasMoved() )
			eval += 40;
		if( elephants[1][1] != NULL && !elephants[0][1]->HasMoved() )
			eval += 40;

		//	don't block the king or queen's pawns in the opening!!!
		if( board.GetSquareContents( 24 ) != NULL &&
			board.GetSquareContents( 14 ) != NULL &&
			!board.GetSquareContents( 14 )->HasMoved() )
			eval -= 160;
		if( board.GetSquareContents( 25 ) != NULL &&
			board.GetSquareContents( 15 ) != NULL &&
			!board.GetSquareContents( 15 )->HasMoved() )
			eval -= 160;
		if( board.GetSquareContents( 94 ) != NULL &&
			board.GetSquareContents( 84 ) != NULL &&
			!board.GetSquareContents( 84 )->HasMoved() )
			eval += 160;
		if( board.GetSquareContents( 95 ) != NULL &&
			board.GetSquareContents( 85 ) != NULL &&
			!board.GetSquareContents( 85 )->HasMoved() )
			eval += 160;
	}
	else
		currentPhase = phases + 1;


	// *** 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
	if( pPawnHash != NULL )
	{
		for( int x = 0; x < board.GetNumberOfPieces( 0 ); x++ )
		{
			if( !board.GetPiece( 0, x )->IsCaptured() &&
				board.GetPiece( 0, x )->GetSquareNumber() < 100 &&
				outpost_10x10[board.GetPiece( 0, x )->GetSquareNumber()] > 0 &&
				board.GetPiece( 0, x )->GetType().gameInt1 > 0 &&
				((int) (pPawnHash->nPawnsPerFile[1][board.files[0][board.GetPiece( 0, x )->GetSquareNumber()]-1]) == 0 ||
				(int) (pPawnHash->backPawnRank[1][board.files[0][board.GetPiece( 0, x )->GetSquareNumber()]-1]) <= board.ranks[0][board.GetPiece( 0, x )->GetSquareNumber()]) &&
				((int) (pPawnHash->nPawnsPerFile[1][board.files[0][board.GetPiece( 0, x )->GetSquareNumber()]+1]) == 0 ||
				(int) (pPawnHash->backPawnRank[1][board.files[0][board.GetPiece( 0, x )->GetSquareNumber()]+1]) <= board.ranks[0][board.GetPiece( 0, x )->GetSquareNumber()]) )
			{
				//	basic bonus for player 0's posted piece
				eval += outpost_10x10[board.GetPiece( 0, x )->GetSquareNumber()] *
						board.GetPiece( 0, x )->GetType().gameInt1;
				int pawnSquare1 = board.GetMovementMatrix( DIRECTION_SE )[board.GetPiece( 0, x )->GetSquareNumber()];
				int pawnSquare2 = board.GetMovementMatrix( DIRECTION_SW )[board.GetPiece( 0, x )->GetSquareNumber()];
				if( board.GetSquareContents( pawnSquare1 ) != NULL &&
					board.GetSquareContents( pawnSquare1 )->GetType().IsPawn() )
					//	additional 50% bonus for this pawn defender
					eval += (outpost_10x10[board.GetPiece( 0, x )->GetSquareNumber()] *
							board.GetPiece( 0, x )->GetType().gameInt1) >> 1;
				if( board.GetSquareContents( pawnSquare2 ) != NULL &&
					board.GetSquareContents( pawnSquare2 )->GetType().IsPawn() )
					//	additional 50% bonus for this pawn defender
					eval += (outpost_10x10[board.GetPiece( 0, x )->GetSquareNumber()] *
							board.GetPiece( 0, x )->GetType().gameInt1) >> 1;
			}
		}
	}

	// *** ROOK ON OPEN and SEMI-OPEN FILE BONUS *** //

	if( pPawnHash != NULL )
	{
		if( rooks[0][0] != NULL &&
			!rooks[0][0]->IsCaptured() &&
			pPawnHash->nPawnsPerFile[0][board.files[0][rooks[0][0]->GetSquareNumber()]] == 0 )
		{
			//	file at least semi-open
			eval += 60;
			if( pPawnHash->nPawnsPerFile[1][board.files[0][rooks[0][0]->GetSquareNumber()]] == 0 )
				//	fully open file
				eval += 30;
		}
		if( rooks[0][1] != NULL &&
			!rooks[0][1]->IsCaptured() &&
			pPawnHash->nPawnsPerFile[0][board.files[0][rooks[0][1]->GetSquareNumber()]] == 0 )
		{
			//	file at least semi-open
			eval += 60;
			if( pPawnHash->nPawnsPerFile[1][board.files[0][rooks[0][1]->GetSquareNumber()]] == 0 )
				//	fully open file
				eval += 30;
		}
		if( rooks[1][0] != NULL &&
			!rooks[1][0]->IsCaptured() &&
			pPawnHash->nPawnsPerFile[1][board.files[0][rooks[1][0]->GetSquareNumber()]] == 0 )
		{
			//	file at least semi-open
			eval -= 60;
			if( pPawnHash->nPawnsPerFile[0][board.files[0][rooks[1][0]->GetSquareNumber()]] == 0 )
				//	fully open file
				eval -= 30;
		}
		if( rooks[1][1] != NULL &&
			!rooks[1][1]->IsCaptured() &&
			pPawnHash->nPawnsPerFile[1][board.files[0][rooks[1][1]->GetSquareNumber()]] == 0 )
		{
			//	file at least semi-open
			eval -= 60;
			if( pPawnHash->nPawnsPerFile[0][board.files[0][rooks[1][1]->GetSquareNumber()]] == 0 )
				//	fully open file
				eval -= 30;
		}
	}
	return *currentPhase;
}

int CitadelChessGame::EnumeratePromotions
	( Piece *piece, 
	  int fromSquare,
	  int toSquare,
	  PieceType **promotions )
{
	int count = 0;
	return count;
}

word32 CitadelChessGame::AdjustPrimaryHash
	( word32 primaryHash )
{
	return primaryHash;
}

void CitadelChessGame::DefaultSettings()
{
	squareColor1 = RGB(255, 255, 220);
	squareColor2 = RGB(150, 175, 161);
	pieceColor1 = RGB(255, 255, 255);
	pieceColor2 = RGB(0, 0, 0);
	borderColor = RGB(108, 0, 0);
	boardDisplayType = BOARD_IS_CHECKERED;
	selectedPieceSet = PIECE_SET_OLD_WORLD;
}
