Example #1
0
static TOffsetMap FindEquivalentSubtries(const TOpaqueTrie& trie, bool verbose, size_t minMergeSize) {
    // Tree nodes, arranged by span length.
    // When all nodes of a given size are considered, they pop off the queue.
    TPieceIndex subtries;
    TOffsetMap merger;
    // Start walking the trie from head.
    AddPiece(subtries, 0, trie.Length);

    size_t counter = 0;
    // Now consider all nodes with sizeable continuations
    for (size_t curlen = trie.Length; curlen >= minMergeSize && !subtries.empty(); curlen--) {
        TPieceIndex::iterator iit = subtries.find(curlen);

        if (iit == subtries.end())
            continue; // fast forward to the next available length value

        TOffsetList& batch = iit->second;
        TPieceComparer comparer(trie.Data, curlen);
        Sort(batch.begin(), batch.end(), comparer);

        TOffsetList::iterator it = batch.begin();
        while (it != batch.end()) {
            if (verbose)
                ShowProgress(++counter);

            size_t offset = *it;

            // Fill the array with the subnodes of the element
            TNode node(trie.Data, offset, trie.SkipFunction);
            size_t end = offset + curlen;
            if (size_t rightOffset = node.GetRightOffset()) {
                AddPiece(subtries, rightOffset, end - rightOffset);
                end = rightOffset;
            }
            if (size_t leftOffset = node.GetLeftOffset()) {
                AddPiece(subtries, leftOffset, end - leftOffset);
                end = leftOffset;
            }
            if (size_t forwardOffset = node.GetForwardOffset()) {
                AddPiece(subtries, forwardOffset, end - forwardOffset);
            }

            while (++it != batch.end()) {
                // Find next different; until then, just add the offsets to the list of merged nodes.
                size_t nextoffset = *it;

                if (memcmp(trie.Data + offset, trie.Data + nextoffset, curlen))
                    break;

                merger.Add(nextoffset, offset);
            }
        }

        subtries.erase(curlen);
    }
    if (verbose) {
        Cerr << counter << Endl;
    }
    return merger;
}
void _PositionStruct::Startup(unsigned char board[10][9]) {
  int sq;
  ClearBoard();
  if ( board != NULL )
  {
      for (int i = 0; i<10;i++)
	      for (int j = 0; j <9; j++){
		      if (board[i][j] > 0){
			      sq = (3+i)*16 + 3 + j;
			      AddPiece(sq, board[i][j]);
		      }
	      }
  }
  else
  {
      int pc;
      for (sq = 0; sq < 256; sq ++) {
        pc = cucpcStartup[sq];
        if (pc != 0) {
          AddPiece(sq, pc);
        }
      }
  }
  SetIrrev();
}
void _PositionStruct::UndoMovePiece(int mv, int pcCaptured) {
  int sqSrc, sqDst, pc;
  sqSrc = SRC(mv);
  sqDst = DST(mv);
  pc = ucpcSquares[sqDst];
  DelPiece(sqDst, pc);
  AddPiece(sqSrc, pc);
  if (pcCaptured != 0) {
    AddPiece(sqDst, pcCaptured);
  }
}
Example #4
0
	void StaticExchangeEvaluator::AddRankFileAttacks()
	{
		ulong rowFileAttackMask = MoveGenerator::rankAttacks[targetSquare][m_board.GetRankStatus(targetSquare)] | 
			MoveGenerator::fileAttacks[targetSquare][m_board.GetFileStatus(targetSquare)];

		ulong rooks = m_board.pieceBitBoards[PieceTypes::Rook];
		AddPiece((rowFileAttackMask & rooks & attackerBits), attackerPieces, PieceTypes::Rook);
		AddPiece((rowFileAttackMask & rooks & defenderBits), defenderPieces, PieceTypes::Rook);

		ulong queens = m_board.pieceBitBoards[PieceTypes::Queen];
		AddPiece((rowFileAttackMask & queens & attackerBits), attackerPieces, PieceTypes::Queen);
		AddPiece((rowFileAttackMask & queens & defenderBits), defenderPieces, PieceTypes::Queen);
	}
Example #5
0
	void StaticExchangeEvaluator::AddDiagonalAttacks()
	{
		ulong diagAttackMask = MoveGenerator::diagA1H8Attacks[targetSquare][m_board.GetDiagA1H8Status(targetSquare)] | 
			MoveGenerator::diagA8H1Attacks[targetSquare][m_board.GetDiagA8H1Status(targetSquare)];
		
		ulong bishops = m_board.pieceBitBoards[PieceTypes::Bishop];
		AddPiece((diagAttackMask & bishops & attackerBits), attackerPieces, PieceTypes::Bishop);
		AddPiece((diagAttackMask & bishops & defenderBits), defenderPieces, PieceTypes::Bishop);

		ulong queens = m_board.pieceBitBoards[PieceTypes::Queen];
		AddPiece((diagAttackMask & queens & attackerBits), attackerPieces, PieceTypes::Queen);
		AddPiece((diagAttackMask & queens & defenderBits), defenderPieces, PieceTypes::Queen);
	}
Example #6
0
	void Board::MakePromotionMove(int move, int source, int destination, int oldPiece)
	{
		int promoType = GetPromoFromMove(move);
		if (promoType != PieceTypes::None)
		{
			RemovePiece(destination, oldPiece);
			int newPiece = Pieces::GetPiece(promoType, turn);
			AddPiece(destination, newPiece);

			ulong oldKey = TranspositionTable::GetPositionKey(destination, oldPiece);
			ulong newKey = TranspositionTable::GetPositionKey(destination, newPiece);
			
			zobristKey ^= oldKey;
			zobristKey ^= newKey;			
			pawnZobristKey ^= oldKey;
			
			positionalScore -= Evaluation::PieceSquareValue(oldPiece, destination);
			positionalScore += Evaluation::PieceSquareValue(newPiece, destination);
			
			endgamePositionalScore -= Evaluation::EndgamePieceSquareValue(oldPiece, destination);
			endgamePositionalScore += Evaluation::EndgamePieceSquareValue(newPiece, destination);
			
			materialScore -= Evaluation::PieceValue(oldPiece);
			materialScore += Evaluation::PieceValue(newPiece);
		}
	}
Example #7
0
// 搬一步棋的棋子
void PositionStruct::MovePiece(int mv) {
  int sqSrc, sqDst, pc;
  sqSrc = SRC(mv);
  sqDst = DST(mv);
  DelPiece(sqDst);
  pc = ucpcSquares[sqSrc];
  DelPiece(sqSrc);
  AddPiece(sqDst, pc);
}
Example #8
0
void Tetris::AddPiece(game_info* gi)
{
	int start_y;
	int start_x =  gi->pos;

	start_y = (gi->fine) / (0.5);

	AddPiece(gi, start_x, start_y);
}
Example #9
0
void Tetris::DropPiece(game_info* gi)
{
	while(!TestCollision(gi))
	{
		gi->fine+=0.25;
	}

	engine.PassMessage(MSG_UPDATEPIECE, gi->pos, gi->curdir, gi->curpiece);
	engine.PassMessage(MSG_UPDATEPIECEY, (unsigned char)((gi->fine / 11.0f) * 255.0f), 0, 0);

	AddPiece(gi);
}
int _PositionStruct::MovePiece(int mv) {
  int sqSrc, sqDst, pc, pcCaptured;
  sqSrc = SRC(mv);
  sqDst = DST(mv);
  pcCaptured = ucpcSquares[sqDst];
  if (pcCaptured != 0) {
    DelPiece(sqDst, pcCaptured);
  }
  pc = ucpcSquares[sqSrc];
  DelPiece(sqSrc, pc);
  AddPiece(sqDst, pc);
  return pcCaptured;
}
Example #11
0
bool
ValueLocation::SetToByteOffset(const ValueLocation& other, uint64 byteOffset,
	uint64 byteSize)
{
	Clear();

	fBigEndian = other.fBigEndian;
	ValuePieceLocation piece = other.PieceAt(0);
	piece.SetToMemory(piece.address + byteOffset);
	piece.SetSize(byteSize);

	return AddPiece(piece);
}
Example #12
0
	void Board::SetText(const string& fen, int playerTurn, CastleRights rights)
	{
		ClearBitboards();

		std::istringstream boardIn(fen);
		char c;
		for(int i=7;i>=0;i--)
		{
			for(int j=0;j<8;j++)
			{
				boardIn >> c;
				if(c != '.')
				{
					int pieceType = PieceTypes::None;
					int color = isupper(c) ? Colors::White : Colors::Black;
					switch (tolower(c))
					{
						case 'q': pieceType = PieceTypes::Queen; break;
						case 'k': pieceType = PieceTypes::King; break;
						case 'r': pieceType = PieceTypes::Rook; break;
						case 'b': pieceType = PieceTypes::Bishop; break;
						case 'n': pieceType = PieceTypes::Knight; break;
						case 'p': pieceType = PieceTypes::Pawn; break;
					}

					AddPiece(Square(i, j), Pieces::GetPiece(pieceType, color));
				}
			}
		}
		turn = playerTurn;
		castleRights = rights;

		
		enPassantRights = EnPassantRights::NoEnPassant;
		
		drawMoveCount = 0;
		turnsPlayed = 0;
		capturedPiece = PieceTypes::None;
		InitializeZobristKey();
		isDrawnByRepetition = false;
	
		isInCheck = IsKingInCheck(turn);
	}
Example #13
0
	void StaticExchangeEvaluator::AddSingleAttacks()
	{
		ulong pawns = m_board.pieceBitBoards[PieceTypes::Pawn];
		AddPiece(MoveGenerator::pawnAttacks[targetSquare][attackerColor] & pawns & attackerBits, attackerPieces, PieceTypes::Pawn);
		AddPiece(MoveGenerator::pawnAttacks[targetSquare][defenderColor] & pawns & defenderBits, defenderPieces, PieceTypes::Pawn);

		ulong knights = m_board.pieceBitBoards[PieceTypes::Knight];
		AddPiece(MoveGenerator::knightAttacks[targetSquare] & knights & attackerBits, attackerPieces, PieceTypes::Knight);
		AddPiece(MoveGenerator::knightAttacks[targetSquare] & knights & defenderBits, defenderPieces, PieceTypes::Knight);

		ulong kings = m_board.pieceBitBoards[PieceTypes::King];
		AddPiece(MoveGenerator::kingAttacks[targetSquare] & kings & attackerBits, attackerPieces, PieceTypes::King);
		AddPiece(MoveGenerator::kingAttacks[targetSquare] & kings & defenderBits, defenderPieces, PieceTypes::King);
	}
Example #14
0
	ulong Board::GetSafeKingMoves(int color)
	{
		ulong safeMoves = 0;	
		int kingSquare = GetKingSquare(color);
		ulong moves = MoveGenerator::kingAttacks[kingSquare];
		ulong newMoves = moves & (~colorBitBoards[color]);
		moves = newMoves;
		if(moves != 0)
		{
			RemovePiece(kingSquare, Pieces::GetPiece(PieceTypes::King, color));
		
			while(moves != 0)
			{
				int move = PopLowestSetBit(moves);
				if(!IsSquareAttacked(move, OtherColor(color)))
				{
					safeMoves |= BitBoard(move);
				}
			}
			AddPiece(kingSquare, Pieces::GetPiece(PieceTypes::King, color));
		}

		return safeMoves; 
	}
Example #15
0
	void Board::UndoMove(int move, bool updateDrawState, const BoardState& undoState)
	{
		updateDrawState = true;
		isInCheck = undoState.isInCheck;
		castleRights = undoState.castleRights;
		enPassantRights = undoState.enPassantRights;
		drawMoveCount = undoState.drawMoveCount;
		materialScore = undoState.materialScore;
		positionalScore = undoState.positionalScore;
		endgamePositionalScore = undoState.endgamePositionalScore;

		if (move != NullMove)
		{
			turnsPlayed--;
			UndoMoveDrawState(updateDrawState);

			int source = GetSourceFromMove(move);
			int dest = GetDestFromMove(move);
			int piece = GetPiece(dest);

			MovePiece(dest, source, piece);
			
			if (GetPromoFromMove(move) != PieceTypes::None)
			{
				RemovePiece(source, piece);
				int oldPiece = Pieces::GetPiece(PieceTypes::Pawn, OtherColor(turn));
				AddPiece(source, oldPiece);
			}

			if (capturedPiece != PieceTypes::None)
			{
				int capture = Pieces::GetPiece(capturedPiece, turn);
				// was this an en passant capture? 
				if (enPassantRights.HasEnPassant() && dest == enPassantRights.CaptureSquare() && Pieces::GetPieceTypeFromPiece(piece) == PieceTypes::Pawn)
				{
					AddPiece(enPassantRights.PawnSquare(), capture);
				}
				else
				{
					AddPiece(dest, capture);
				}
			}

			// if this was a castle move, restore the rook
			if (Pieces::GetPieceTypeFromPiece(piece) == PieceTypes::King)
			{
				int delta = dest - source;
				if(delta == 2 || delta == -2)
				{
					int rookOrigin = dest + delta / 2;
					if(delta < 0)
					{
						rookOrigin--;
					}
					int rookDestination = dest - delta / 2;
					int rook = Pieces::GetPiece(PieceTypes::Rook, OtherColor(turn));
					MovePiece(rookDestination, rookOrigin, rook);
				}
			}

			capturedPiece = undoState.capturedPiece;
		}

		turn = OtherColor(turn);
		zobristKey = undoState.zobristKey;
		pawnZobristKey = undoState.pawnZobristKey;
	}
Example #16
0
	void Board::SetFEN(const string& fen)
	{
		ClearBitboards();

		std::istringstream fenIn(fen);
		string chunk;
		fenIn >> chunk;
		int row = 7, col = 0;
		for (unsigned int i=0;i<chunk.size();i++)
		{
			char c = chunk[i];
			if (c == '/')
			{
				row--;
				col = 0;
			}
			else
			{
				if (isdigit(c))
				{
					col += c - '0';
				}
				else
				{
					int pieceType = PieceTypes::None;
					int color = isupper(c) ? Colors::White : Colors::Black;
					switch (tolower(c))
					{
						case 'q': pieceType = PieceTypes::Queen; break;
						case 'k': pieceType = PieceTypes::King; break;
						case 'r': pieceType = PieceTypes::Rook; break;
						case 'b': pieceType = PieceTypes::Bishop; break;
						case 'n': pieceType = PieceTypes::Knight; break;
						case 'p': pieceType = PieceTypes::Pawn; break;
					}

					AddPiece(Square(row, col), Pieces::GetPiece(pieceType, color));
					col++;
				}
			}
		}
		fenIn >> chunk;

		turn = chunk[0] == 'w' ? Colors::White : Colors::Black;
		castleRights = CastleRights(true, true, true, true);

		fenIn >> chunk;
		if (chunk.find('K') == string::npos) castleRights.ClearWhiteKing();
		if (chunk.find('Q') == string::npos) castleRights.ClearWhiteQueen();
		if (chunk.find('k') == string::npos) castleRights.ClearBlackKing();
		if (chunk.find('q') == string::npos) castleRights.ClearBlackQueen();
		
		fenIn >> chunk;
		// handle EP
		if (chunk == "-")
		{
			enPassantRights = EnPassantRights::NoEnPassant;
		}
		else
		{
			int epcol = chunk[0] - 'a';
			int eprow = chunk[1] - '1';
			enPassantRights = EnPassantRights(eprow, epcol);
		}

		// handle draw count
		fenIn >> drawMoveCount;

		fenIn >> turnsPlayed;

		capturedPiece = PieceTypes::None;
		InitializeZobristKey();
		isDrawnByRepetition = false;
	
		isInCheck = IsKingInCheck(turn);
	}
Example #17
0
ValueLocation::ValueLocation(bool bigEndian, const ValuePieceLocation& piece)
	:
	fBigEndian(bigEndian)
{
	AddPiece(piece);
}
Example #18
0
void Tetris::Update(game_info* gi, float deltatime)
{
	if (gi->state == STATE_TETRIS_TRANS)
	{
		gi->rot2 += TRANSITION_SPEED * deltatime;

		if (gi->rot2 >= 180)
		{
			gi->rot2 = 180;
			engine.ChangeState(gi, STATE_BREAKOUT);
		}

		engine.PassMessage(MSG_ROT_BOARD2, (gi->rot2 / 180.0f) * 255.0f, 0,0);
		return;
	}

	if (gi->attacking)
	{
		gi->rot += TETRIS_ATTACK_ROT_SPEED * deltatime;
		gi->attack_rot += TETRIS_ATTACK_ROT_SPEED * deltatime;

		if (gi->attack_rot >= 360)
		{
			gi->rot = -BOARD_NORMAL_ROT;
			gi->attack_rot = 0;

			gi->attacking = 0;

			gi->score += (10 * 100);
			engine.PassMessage(MSG_APPENDSCORE, 100, 10, 0);
		}

		engine.PassMessage(MSG_ROT_BOARD, (gi->rot / 360.0f) * 255.0f, 0,0);
	}


	if (!engine.network_thread)
	{
		if (engine.keys[SDLK_DOWN])
		{
			gi->fine += deltatime * (TETRIS_SPEED + 4.3 + 0.3 * LEVEL);
		}
		else
		{
			gi->fine += deltatime * (TETRIS_SPEED + 0.3 * LEVEL);
		}
	}
	else
	{
		if (engine.keys[SDLK_DOWN])
		{
			gi->fine += deltatime * (TETRIS_SPEED + 4.3);
		}
		else
		{
			gi->fine += deltatime * TETRIS_SPEED;
		}
	}

	//gi->rot2+=50.0 * deltatime;

	if (TestCollision(gi))
	{
		// we collided! oh no!
		if (TestGameOver(gi))
		{
			engine.GameOver();
		}
		else
		{
			AddPiece(gi);
		}
	}

	//printf("%f\n", gi->fine);
	engine.PassMessage(MSG_UPDATEPIECEY, (unsigned char)((gi->fine / 11.0f) * 255.0f), 0, 0);
}
Example #19
0
bool
ValueLocation::SetTo(const ValueLocation& other, uint64 bitOffset,
	uint64 bitSize)
{
	Clear();

	fBigEndian = other.fBigEndian;

	// compute the total bit size
	int32 count = other.CountPieces();
	uint64 totalBitSize = 0;
	for (int32 i = 0; i < count; i++) {
		const ValuePieceLocation &piece = other.PieceAt(i);
		totalBitSize += piece.bitSize;
	}

	// adjust requested bit offset/size to something reasonable, if necessary
	if (bitOffset + bitSize > totalBitSize) {
		if (bitOffset >= totalBitSize)
			return true;
		bitSize = totalBitSize - bitOffset;
	}

	if (fBigEndian) {
		// Big endian: Skip the superfluous most significant bits, copy the
		// pieces we need (cutting the first and the last one as needed) and
		// ignore the remaining pieces.

		// skip pieces for the most significant bits we don't need anymore
		uint64 bitsToSkip = bitOffset;
		int32 i;
		ValuePieceLocation piece;
		for (i = 0; i < count; i++) {
			const ValuePieceLocation& tempPiece = other.PieceAt(i);
			if (tempPiece.bitSize > bitsToSkip) {
				if (!piece.Copy(tempPiece))
					return false;
				break;
			}
			bitsToSkip -= tempPiece.bitSize;
		}

		// handle partial piece
		if (bitsToSkip > 0) {
			piece.bitOffset += bitsToSkip;
			piece.bitSize -= bitsToSkip;
			piece.Normalize(fBigEndian);
		}

		// handle remaining pieces
		while (bitSize > 0) {
			if (piece.bitSize > bitSize) {
				// the piece is bigger than the remaining size -- cut it
				piece.bitSize = bitSize;
				piece.Normalize(fBigEndian);
				bitSize = 0;
			} else
				bitSize -= piece.bitSize;

			if (!AddPiece(piece))
				return false;

			if (++i >= count)
				break;

			if (!piece.Copy(other.PieceAt(i)))
				return false;
		}
	} else {
		// Little endian: Skip the superfluous least significant bits, copy the
		// pieces we need (cutting the first and the last one as needed) and
		// ignore the remaining pieces.

		// skip pieces for the least significant bits we don't need anymore
		uint64 bitsToSkip = totalBitSize - bitOffset - bitSize;
		int32 i;
		ValuePieceLocation piece;
		for (i = 0; i < count; i++) {
			const ValuePieceLocation& tempPiece = other.PieceAt(i);
			if (tempPiece.bitSize > bitsToSkip) {
				if (!piece.Copy(tempPiece))
					return false;
				break;
			}
			bitsToSkip -= piece.bitSize;
		}

		// handle partial piece
		if (bitsToSkip > 0) {
			piece.bitSize -= bitsToSkip;
			piece.Normalize(fBigEndian);
		}

		// handle remaining pieces
		while (bitSize > 0) {
			if (piece.bitSize > bitSize) {
				// the piece is bigger than the remaining size -- cut it
				piece.bitOffset += piece.bitSize - bitSize;
				piece.bitSize = bitSize;
				piece.Normalize(fBigEndian);
				bitSize = 0;
			} else
				bitSize -= piece.bitSize;

			if (!AddPiece(piece))
				return false;

			if (++i >= count)
				break;

			if (!piece.Copy(other.PieceAt(i)))
				return false;
		}
	}

	return true;
}
Example #20
0
void FromFen(const char *szFen) {
  int i, j, k;
  int pcWhite[7];
  int pcBlack[7];
  const char *lpFen;
  // FEN串的识别包括以下几个步骤:
  // 1. 初始化,清空棋盘
  pcWhite[0] = SIDE_TAG(0) + KING_FROM;
  pcWhite[1] = SIDE_TAG(0) + ADVISOR_FROM;
  pcWhite[2] = SIDE_TAG(0) + BISHOP_FROM;
  pcWhite[3] = SIDE_TAG(0) + KNIGHT_FROM;
  pcWhite[4] = SIDE_TAG(0) + ROOK_FROM;
  pcWhite[5] = SIDE_TAG(0) + CANNON_FROM;
  pcWhite[6] = SIDE_TAG(0) + PAWN_FROM;
  for (i = 0; i < 7; i ++) {
    pcBlack[i] = pcWhite[i] + 16;
  }
  /* 数组"pcWhite[7]"和"pcBlack[7]"分别代表红方和黑方每个兵种即将占有的序号,
   * 以"pcWhite[7]"为例,由于棋子16到31依次代表“帅仕仕相相马马车车炮炮兵兵兵兵兵”,
   * 所以最初应该是"pcWhite[7] = {16, 17, 19, 21, 23, 25, 27}",每添加一个棋子,该项就增加1,
   * 这种做法允许添加多余的棋子(例如添加第二个帅,就变成仕了),但添加前要做边界检测
   */
//  ClearBoard();
  lpFen = szFen;
  if (*lpFen == '\0') {
 //   SetIrrev();
    return;
  }
  // 2. 读取棋盘上的棋子
  i = RANK_TOP;
  j = FILE_LEFT;
  while (*lpFen != ' ') {
    if (*lpFen == '/') {
      j = FILE_LEFT;
      i ++;
      if (i > RANK_BOTTOM) {
        break;
      }
    } else if (*lpFen >= '1' && *lpFen <= '9') {
      for (k = 0; k < (*lpFen - '0'); k ++) {
        if (j >= FILE_RIGHT) {
          break;
        }
        j ++;
      }
    } else if (*lpFen >= 'A' && *lpFen <= 'Z') {
      if (j <= FILE_RIGHT) {
        k = FenPiece(*lpFen);
        if (k < 7) {
          if (pcWhite[k] < 32) {
            //if (this->ucsqPieces[pcWhite[k]] == 0) {
              AddPiece(COORD_XY(j, i), pcWhite[k]);
              pcWhite[k] ++;
            //}
          }
        }
        j ++;
      }
    } else if (*lpFen >= 'a' && *lpFen <= 'z') {
      if (j <= FILE_RIGHT) {
        //k = FenPiece(*lpFen + 'A' - 'a');
        k = FenPiece(*lpFen);
        if (6<k < 14) {
          if (pcBlack[k-7] < 48) {
            //if (this->ucsqPieces[pcBlack[k]] == 0) {
              AddPiece(COORD_XY(j, i), pcBlack[k-7]);
              pcBlack[k-7] ++;
            //}
          }
        }
        j ++;
      }
    }
    lpFen ++;
    if (*lpFen == '\0') {
      //SetIrrev();
      return;
    }
  }
  lpFen ++;
  // 3. 确定轮到哪方走
//  if (this->sdPlayer == (*lpFen == 'b' ? 0 : 1)) {
//    ChangeSide();
//  }
//  // 4. 把局面设成“不可逆”
//  SetIrrev();
}
Example #21
0
void ChessBoard::UndoMove()
{
	Player* currPlayer;
	Player* opponentPlayer;
	bool bKingMoved = false;
	int col;
	if (bWhiteMove)
	{
		currPlayer = _BlackPlayer;
		opponentPlayer = _WhitePlayer;
		col = 7;
	}
	else {
		currPlayer = _WhitePlayer;
		opponentPlayer = _BlackPlayer;
		col = 0;
	}

	ChessMove* moveToUndo = _ChessLogInstance->getLastMove();
	if ( moveToUndo->isCastle() )
	{
		if (moveToUndo->isKingSideCastle())
		{
			ChessPiece* king = GetPiece(6, col); 
			if(pieceToText(king) != 'K')
				ChessAssert();
			ChessPiece* rook = GetPiece(5, col);
			if(pieceToText(rook) != 'R')
				ChessAssert();
			rook->SetRow(7);
			king->SetRow(4);
			
			Board[4][col] = king;
			Board[6][col] = NULL;
			Board[5][col] = NULL;
			Board[7][col] = rook;
			
			(dynamic_cast<King*>(king))->SetHasMoved(false);
			(dynamic_cast<King*>(king))->SetHasCastled(false);
			(dynamic_cast<Rook*>(rook))->SetHasMoved(false);
			ResolveLineOfSight(rook);
		}
		else {
			ChessPiece* king = GetPiece(2, col); 
			if(pieceToText(king) != 'K')
				ChessAssert();
			ChessPiece* rook = GetPiece(3, col);
			if(pieceToText(rook) != 'R')
				ChessAssert();
			rook->SetRow(0);
			king->SetRow(4);
			
			Board[4][col] = king;
			Board[3][col] = NULL;
			Board[2][col] = NULL;
			Board[0][col] = rook;
			(dynamic_cast<King*>(king))->SetHasMoved(false);
			(dynamic_cast<King*>(king))->SetHasCastled(false);
			(dynamic_cast<Rook*>(rook))->SetHasMoved(false);
			ResolveLineOfSight(rook);
		}
		bKingMoved = true;

	}
	//NEED TO CHECK FOR PAWN PROMOTION HERE
	else if ( moveToUndo->isPromotion() )
	{
		ChessPiece* newPromoPiece = GetPiece(moveToUndo->getRow(), moveToUndo->getCol());
		ChessSquare PromotionSquare = ChessSquare(moveToUndo->getRow(), moveToUndo->getCol());
		currPlayer->UndoPawnPromotion(moveToUndo->getStartingRow(), PromotionSquare, newPromoPiece);
		Board[moveToUndo->getRow()][moveToUndo->getCol()] = NULL;
		if (PromotionSquare.row != moveToUndo->getStartingRow())
		{
			ChessPiece* capturedPiece = opponentPlayer->FindCapturedPiece(moveToUndo->getRow(), moveToUndo->getCol(), moveToUndo->getCapturedPiece());
			if(!capturedPiece)
				ChessAssert();
			ChessSquare capturedPieceLoc = capturedPiece->GetLocation();
			if (Board[capturedPieceLoc.row][capturedPieceLoc.col] != NULL )
				ChessAssert();
			opponentPlayer->RebirthCapturedPiece(capturedPiece);
			AddPiece(capturedPiece);
		}
		//printf("Undid pawn promotion below: \n");
		//ChessBoard::GetInstance()->PrintBoard();
	}
	else if ( moveToUndo->IsEnPassant() )
	{
		ChessPiece* capturedPiece = opponentPlayer->FindCapturedPiece(moveToUndo->getRow(), moveToUndo->getStartingCol(), moveToUndo->getCapturedPiece());
		if(!capturedPiece)
			ChessAssert();
		ChessPiece* movedPiece = GetPiece(moveToUndo->getRow(), moveToUndo->getCol() );
		
		Board[moveToUndo->getRow()][moveToUndo->getCol()] = NULL;
		Board[moveToUndo->getRow()][moveToUndo->getStartingCol()] = capturedPiece;
		Board[moveToUndo->getStartingRow()][moveToUndo->getStartingCol()] = movedPiece;
		
		movedPiece->SetRow(moveToUndo->getStartingRow());
		movedPiece->SetCol(moveToUndo->getStartingCol());
		
		//AddPiece(capturedPiece);
		ResolveLineOfSight(capturedPiece);
		opponentPlayer->RebirthCapturedPiece(capturedPiece);
		ResolveLineOfSight(movedPiece);
	}
	else if ( moveToUndo->isCapture() )
	{
		ChessPiece* capturedPiece = moveToUndo->getCapturedPiece();
		if (!capturedPiece)
			ChessAssert();
		ChessPiece* movedPiece = GetPiece(moveToUndo->getRow(), moveToUndo->getCol() );
		
		Board[moveToUndo->getRow()][moveToUndo->getCol()] = capturedPiece;
		Board[moveToUndo->getStartingRow()][moveToUndo->getStartingCol()] = movedPiece;
		
		movedPiece->SetRow(moveToUndo->getStartingRow());
		movedPiece->SetCol(moveToUndo->getStartingCol());
		
		if (pieceToText(movedPiece) == 'K')
		{
			(dynamic_cast<King*>(movedPiece))->SetHasMoved(false);
			bKingMoved = true;
		}
		else if (pieceToText(movedPiece) == 'R')
			(dynamic_cast<Rook*>(movedPiece))->SetHasMoved(false);
		
		ResolveLineOfSight(capturedPiece);
		opponentPlayer->RebirthCapturedPiece(capturedPiece);
		ResolveLineOfSight(movedPiece);
	}
	else
	{
		ChessPiece* movedPiece = GetPiece(moveToUndo->getRow(), moveToUndo->getCol() );
		Board[moveToUndo->getRow()][moveToUndo->getCol()] = NULL;
		Board[moveToUndo->getStartingRow()][moveToUndo->getStartingCol()] = movedPiece;
		movedPiece->SetRow(moveToUndo->getStartingRow());
		movedPiece->SetCol(moveToUndo->getStartingCol());
		
		if (pieceToText(movedPiece) == 'K')
		{
			(dynamic_cast<King*>(movedPiece))->SetHasMoved(false);
			bKingMoved = true;
		}
		else if (pieceToText(movedPiece) == 'R')
			(dynamic_cast<Rook*>(movedPiece))->SetHasMoved(false);
		ResolveLineOfSight(movedPiece);
	}
	
	if (bKingMoved)
	{
		currPlayer->ClearCheckState();
		opponentPlayer->ClearAttackingKingPieces();
		
		ChessSquare kingLoc = currPlayer->GetKingLocation();
		for (int i = 0; i < opponentPlayer->GetNumPiecesLeft(); i++)
		{
			if (CheckForCheck(opponentPlayer->GetPiece(i)) )
			{
				currPlayer->EnterCheckState();
				//printf("Checking Piece: %c", pieceToText(currPlayer->GetAttackingKingPiece(i)));
				//fflush(stdout);
				opponentPlayer->AddToKingAttacking(opponentPlayer->GetPiece(i));
			}
			else if (opponentPlayer->GetPiece(i)->HasLineToKing(kingLoc))
				opponentPlayer->AddToKingAttacking(opponentPlayer->GetPiece(i));
		}
	}
	else 
	{
		for (int i = 0; i < opponentPlayer->GetNumAttackingKingPieces(); i++)
		{
			if (CheckForCheck(opponentPlayer->GetAttackingKingPiece(i)) )
			{
				currPlayer->EnterCheckState();
				//printf("Checking Piece: %c", pieceToText(opponentPlayer->GetAttackingKingPiece(i)));
				//fflush(stdout);
				break;
			}
			if (i == (opponentPlayer->GetNumAttackingKingPieces() - 1))
				currPlayer->ClearCheckState();
		}
	}

	
	for (int i = 0; i < currPlayer->GetNumAttackingKingPieces(); i++)
	{
		if (CheckForCheck(currPlayer->GetAttackingKingPiece(i)) )
		{
			opponentPlayer->EnterCheckState();
			//printf("Checking Piece: %c", pieceToText(currPlayer->GetAttackingKingPiece(i)));
			//fflush(stdout);
			break;
		}
		if (i == (currPlayer->GetNumAttackingKingPieces() - 1))
			opponentPlayer->ClearCheckState();
	}
	
	_ChessLogInstance->removeLastItemFromLog();
	
	bWhiteMove = !bWhiteMove;
	bBlackMove = !bBlackMove;
	//REMOVE BELOW WHEN WORKING
	ChessSquare currPlayerKing = currPlayer->GetKingLocation();
	/*for (int i = 0; i < opponentPlayer->GetNumPiecesLeft(); i++)
	{
		if (opponentPlayer->GetPiece(i)->HasLineToKing(currPlayerKing) )
		{
			if (!(opponentPlayer->GetPiece(i)->IsInKingArray()))
			{
				ChessPiece* forTestPiece = opponentPlayer->GetPiece(i);
				forTestPiece->HasLineToKing(currPlayerKing);
				ChessAssert();
			}
		}
		else {
			if (opponentPlayer->GetPiece(i)->IsInKingArray())
				ChessAssert();
		}

	}
	ChessSquare opponentPlayerKing = opponentPlayer->GetKingLocation();
	for (int i = 0; i < currPlayer->GetNumPiecesLeft(); i++)
	{
		if (currPlayer->GetPiece(i)->HasLineToKing(opponentPlayerKing) )
		{
			if (!(currPlayer->GetPiece(i)->IsInKingArray()))
				ChessAssert();
		}
		else {
			if (currPlayer->GetPiece(i)->IsInKingArray())
				ChessAssert();
		}
		
	}*/
}
Example #22
0
void CPieceUnitEditImp::AddPieceUnit(CPieceUnitInfo& PieceUnitInfo, CEditPiece* Piece )
{
	AddPiece(PieceUnitInfo, Piece);
}