Example #1
0
void ChessBoard::generatePawnMoves(ChessBoard& board, int sqSrc, Moves& mvs)
{
    int sqDst;

    if (board.m_sdPlayer != SQ_SIDE(sqSrc))
    {
        sqDst = sqSrc - 1;
        if (IN_BOARD(sqDst) && board.canMove(board, sqSrc, sqDst))
        {
            mvs.append(ChessBoard::mv(sqSrc, sqDst));
        }
        sqDst = sqSrc + 1;
        if (IN_BOARD(sqDst) && board.canMove(board, sqSrc, sqDst))
        {
            mvs.append(ChessBoard::mv(sqSrc, sqDst));
        }
    }


    if (board.m_sdPlayer==0)
    {
        sqDst = sqSrc - 16;
    }
    else{
        sqDst = sqSrc + 16;
    }
    if (IN_BOARD(sqDst) && board.canMove(board, sqSrc, sqDst))
    {
        mvs.append(ChessBoard::mv(sqSrc, sqDst));
    }
}
Example #2
0
void WriteEmail ( const ChessBoard &board, const char *filename )
{
    FILE *f = fopen ( filename, "wt" );
    if ( !f )
    {
        sprintf ( ExitMessage, "Error opening file '%s' for write!\n", filename );
        exit(1);
    }

    ListChessGame ( board, f );
    fprintf ( f, "\n\n%s", ChessDataStart );

    unsigned n = board.GetCurrentPlyNumber();

    fprintf ( f, "%u\n", n );

    for ( unsigned i=0; i < n; i++ )
    {
        Move move = board.GetPastMove ( i );
        // Write source, dest codes as ASCII data...

        fprintf ( f, "%02X %02X\n", unsigned(move.source), unsigned(move.dest) );
    }

    fprintf ( f, "%s", ChessDataEnd );
    fclose ( f );
}
Example #3
0
void Engine::search(ChessBoard& board, MoveList& moves, SEARCHTYPE searchtype, int wtime, int winc, int btime, int binc, int movestogo)
{
	if (!process)
		return;
	QString cmd;
	QStringList list;
	ChessBoard b;
	int i;
	currentBoard = board;
	for (i = 0; i < moves.size; i++)
	{
		list.append(currentBoard.makeMoveText(moves.at(i),UCI).c_str());
		if (!currentBoard.doMove(moves.at(i), true))
			break;
	}
	string s=board.getFen();
	cmd = "position fen ";

	if (board.startposition())
		cmd += "startfen";
	else
		cmd += board.getFen(true).c_str();
	if (list.size())
	{
		cmd += " moves";
		QStringList::iterator lit = list.begin();
		while (lit != list.end())
		{
			cmd += " ";
			cmd += *lit;
			++lit;
		}
	}
	// If engine playing white it is most probaly not ready yet.
	if (readyok)
		write(cmd);
	else
		waitCommand += cmd;
	cmd="go";
	if (searchtype == PONDER_SEARCH)
		cmd += " ponder";
	if (searchtype == INFINITE_SEARCH)
	{
		cmd += " infinite";
	}
	else
	{
		cmd += " wtime " + QString().setNum(wtime);
		cmd += " btime " + QString().setNum(btime);
		cmd += " winc " + QString().setNum(winc);
		cmd += " binc " + QString().setNum(binc);
	}
	if (movestogo)
		cmd += "movestogo " + QString().setNum(movestogo);
	cmd += "\n";
	if (readyok)
		write(cmd);
	else
		waitCommand += cmd;
}
Example #4
0
JNIEXPORT void JNICALL Java_jwtc_chess_JNI_putPiece( JNIEnv* env, jobject thiz, jint pos, jint piece, jint turn)
{
	ChessBoard *board = stGame->getBoard();
	board->put(pos, piece, turn);

	//DEBUG_PRINT("Put [%d, %d, %d]\n", pos, piece, turn);
}
Example #5
0
bool FrameFunc2()
{
	if(ExitBtn->Clicked())
	{
		rplystop(false);
		return false;
	}
	
	if(rplypos > replay.size() - 3)
	{
		rplystop(true);
		return false;
	}

	ChessClr clr = ChessClr(replay.at(rplypos));
	rplypos++;
	int x = ChessClr(replay.at(rplypos));
	rplypos++;
	int y = ChessClr(replay.at(rplypos));
	rplypos++;

	board.set_cclr(ChessClr(-clr));
	char dir[9];
	board.Power(x, y, clr, dir);
	if(dir[8]) board.SetChess(x, y, clr, dir);

	Sleep(1000);
	return false;
}
Example #6
0
bool InternetChessPlayer::send ( const ChessBoard &board )
{
    char tempString [256];

    UINT32 numPlies = board.GetCurrentPlyNumber();
    if ( numPlies > 0 )
    {
        // Before receiving the move from the remote opponent, we must
        // send him the complete state of the game as it exists locally.

        // Send an 8-byte string to specify what kind of message this is.
        // In this case, it is "history", because we are sending the entire history
        // of moves in the game history so far...

        UINT32 plyBytes = numPlies * sizeof(Move);
        UINT32 packetSize = 8 + sizeof(numPlies) + plyBytes;
        int result = ::send ( connectInfo.commSocket, (const char *)&packetSize, 4, 0 );
        if ( result != 4 )
        {
            sprintf ( tempString, "send psize: %d", WSAGetLastError() );
            userInterface.ReportSpecial (tempString);
            return false;
        }

        result = ::send ( connectInfo.commSocket, "history ", 8, 0 );
        if ( result != 8 )
        {
            sprintf ( tempString, "send 'history': %d", WSAGetLastError() );
            userInterface.ReportSpecial (tempString);
            return false;
        }

        result = ::send ( connectInfo.commSocket, (const char *)&numPlies, 4, 0 );
        if ( result != 4 )
            return false;

        Move *history = new Move [numPlies];
        if ( !history )
        {
            userInterface.ReportSpecial ( "out of memory!" );
            return false;
        }

        for ( UINT32 ply = 0; ply < numPlies; ++ply )
            history[ply] = board.GetPastMove (ply);

        result = ::send ( connectInfo.commSocket, (const char *)history, plyBytes, 0 );
        delete[] history;
        history = NULL;

        if ( UINT32(result) != plyBytes )
        {
            sprintf ( tempString, "send: %d", WSAGetLastError() );
            userInterface.ReportSpecial (tempString);
            return false;
        }
    }

    return true;
}
Example #7
0
void CalculatePositionHashes (LearnBranch *table, int tablesize, ChessBoard &board, int node)
{
    UnmoveInfo  unmove;

    assert (node >= 0);
    assert (node < tablesize);

    int myhash = board.Hash();

    do
    {
        ++NumHashPositions;
        table[node].reserved[0] = myhash;
        if (table[node].child >= 0)
        {
            board.MakeMove (table[node].move, unmove);
            CalculatePositionHashes (table, tablesize, board, table[node].child);
            board.UnmakeMove (table[node].move, unmove);
            int checkhash = board.Hash();
            assert (checkhash == myhash);
        }
        node = table[node].sibling;
    }
    while (node >= 0);

    assert (node == -1);
}
void PgntestTest::ChessBoard_checkFigureMove()
{
    ChessBoard cb;
    pgn::Ply ply("Nf3");
    cb.makeMove(White, ply);
    QCOMPARE((int)cb.getPiece(2, 5).type, (int)Knight);
}
Example #9
0
bool RenderFunc()
{
	hge->Gfx_BeginScene();
	hge->Gfx_Clear(ARGB(255, 0x8c, 0x78, 0x53));

	//Chessboard
	HGECB->Render();
	//cursor
	Cur->Render();
	//score board
	HFont->printf(BTN2_X, BLBL_Y, 0, "Black: %d", board.GetBNum());
	HFont->printf(BTN2_X, WLBL_Y, 0, "White: %d", board.GetWNum());
	char *p = (board.get_cclr() == Black) ? "Black" : "White";
	HFont->printf(BTN2_X, NOWLBL_Y, 0, "Now: %s", p);
	Timer->Render();
	//sidebar
	SaveBtn->Render();
	LoadBtn->Render();
	UndoBtn->Render();
	ExitBtn->Render();
	HintBtn->Render();
	
	hge->Gfx_EndScene();
	return false;
}
Example #10
0
void Own2::AI(uint8 inp)
{
    hash = ZobristHash(hash,inp,choose,0);
    ChessBoard *rootChessBoard = new ChessBoard(a,hash);
    int16 output = rootChessBoard->run();
    delete rootChessBoard;
    int p = 0;
//    while (p == 0)
//    {
//        (time(NULL)) ;//通过系统时间初始化随机数种子
        int m = output / 16;
        int n = output % 16;
        int q = 3-choose;

        if(a[m][n] == 0 )
        {
            a[m][n] = q;
            p = 1;
            if(Win(m, n))
            {
                update();
                int ch = choose;
                if (ch==2) QMessageBox::information(this, "Win", "Black Win", QMessageBox::Ok);

                if (ch==1) QMessageBox::information(this, "Win", "White Win", QMessageBox::Ok);
            }
        }
//    }
        realPly++;
}
void PgntestTest::ChessBoard_checkSimpleMove()
{
    ChessBoard cb;
    pgn::Ply ply("e4");
    cb.makeMove(White, ply);
    QCOMPARE((int)cb.getPiece(3, 4).type, (int)Pawn);
}
Example #12
0
void testSetupQuiesce()
{
	char buf[1024] = "", s[255];
	ChessBoard *board = g->getBoard();
	
	board->put(ChessBoard::d7, ChessBoard::PAWN, ChessBoard::BLACK);
	board->put(ChessBoard::f8, ChessBoard::KING, ChessBoard::BLACK);
	board->put(ChessBoard::c6, ChessBoard::PAWN, ChessBoard::BLACK);
	board->put(ChessBoard::e7, ChessBoard::QUEEN, ChessBoard::BLACK);
	
	
	board->put(ChessBoard::b4, ChessBoard::BISHOP, ChessBoard::WHITE);
	board->put(ChessBoard::c3, ChessBoard::PAWN, ChessBoard::WHITE);
	board->put(ChessBoard::d4, ChessBoard::PAWN, ChessBoard::WHITE);
	board->put(ChessBoard::e5, ChessBoard::PAWN, ChessBoard::WHITE);
	board->put(ChessBoard::d3, ChessBoard::KING, ChessBoard::WHITE);
	
	board->setCastlingsEPAnd50(0, 0, 0, 0, -1, 0);
	board->setTurn(0);
	g->commitBoard();
	
	board->toFEN(buf);
	DEBUG_PRINT(buf, 0);
	

}
Example #13
0
// static
Move MoveChecker::complete(IncompleteMove incomplete_move,
                           const ChessBoard& board)
{
  const Position src(incomplete_move.source());
  const Piece::piece_index_t piece_index = board.piece_index(src);
  const Position dst(incomplete_move.destination());
  const int color_index = static_cast<int>(board.turn_color());
  if (BitBoard(src) & BitBoard(MagicNumbers::c_king_positions[color_index])
      && BitBoard(dst) & BitBoard(MagicNumbers::c_castle_squares[color_index])
      && piece_index == PieceSet::c_king_index) {
    if (dst.column() == Position::c_kings_knight_column) {
      return Move(src, dst, Move::c_castle_k_flag);
    } else {
      assert(dst.column() == Position::c_queens_bishop_column);
      return Move(src, dst, Move::c_castle_q_flag);
    }
  }
  const BitBoard capturable = board.opponents();
  const BitBoard dst_board(dst);
  const bool is_capture = capturable & dst_board;
  if (piece_index == PieceSet::c_pawn_index) {
    if (board.ep_captures() & dst_board) {
      return Move(src, dst, Move::c_ep_flag);
    } else if (incomplete_move.is_promotion()) {
      const uint16_t flags = (static_cast<uint16_t>(is_capture) << 14) | incomplete_move.m_state;
      return Move(src, dst, flags);
    } else if (abs(src.row() - dst.row()) == 2) {
      return Move(src, dst, Move::c_double_pawn_push_flag);
    }
  }
  return Move(src, dst, is_capture << 14);
}
Example #14
0
void Edit_DrawBoard ( const ChessBoard &board )
{
    const SQUARE *b = board.queryBoardPointer();
    printf ( "   +--------+\n" );
    for ( int y=9; y >= 2; --y )
    {
        printf ( " %d |", y-1 );
        for ( int x=2; x <= 9; ++x )
        {
            char c = PieceRepresentation ( b[OFFSET(x,y)] );
            printf ( "%c", c );
        }

        printf ( "|" );

        if ( y == 6 )
            printf ( "   ply  = %d", board.GetCurrentPlyNumber() );
        else if ( y == 5 )
            printf ( "   hash = %08lx", (unsigned long)(board.Hash()) );

        printf ( "\n" );
    }
    printf ( "   +--------+\n" );
    printf ( "    abcdefgh\n\n" );
}
Example #15
0
int main()
{
	ChessBoard mainBoard;
	GUI::initializeBoard(mainBoard);
	GUI::displayBoard(mainBoard);

	while (!mainBoard.getCheckmate()) // Move cycle.
	{
		string userInput;
		cin >> userInput;
		if (Input::isSentinelValue(userInput)) // Sentinel values are "end" and "forfeit."
		{
			break;
		}
		if (Input::isDiagnosticTest(userInput, mainBoard) || !Input::isMove(userInput))
		{
			continue;
		}
		Input* move = Input::interpretInput(userInput); // Converts user input into integer values.

		ChessPiece* movingPiece = mainBoard.ChessBoard::getPieceAt(move->getFromX(), move->getFromY()); // Figures out which piece is being moved.
		bool isPiece = (movingPiece != nullptr);
		if (isPiece)
		{
			bool isValidMove = Rules::isValidMove(mainBoard, *movingPiece, move);
			if (!isValidMove)
			{
				continue;
			}

			ChessPiece* removedPiece = mainBoard.movePiece(*movingPiece, move->getToX(), move->getToY()); // If it doesn't violate basic movement rules, the piece is moved to its new location.

			bool compliesWithCheckRules = Rules::compliesWithCheckRules(mainBoard, *movingPiece, removedPiece, move);
			if (!compliesWithCheckRules)
			{
				continue;
			}

			bool gameover = mainBoard.getCheckmate();
			if (gameover)
			{
				break;
			}
		}
		else
		{
			cout << "That is not a piece\n\n";
			continue;
		}

		cout << string(50, '\n'); // "Clears" old board.
		GUI::displayBoard(mainBoard); // Displays new board.
		mainBoard.nextTurn(); // It's now the other player's turn.
	}
	cin.ignore();
	return 0;
}
void PgntestTest::PawnMoveChecker_checkPossibleEnPassante()
{
    ChessBoard cb;
    cb.clear();


    PawnMoveChecker checker;

    QVERIFY(checker.canMoveTo(1, 0, White, 3, 0, cb));
}
void PgntestTest::BasicMoveChecker_doNotMoveOnFrienCell()
{
    ChessBoardPiece piece;
    piece.color = White;
    piece.type = Rook;

    ChessBoard cb;
    cb.setPiece(5, 5, piece);
    BasicMoveChecker checker;
    QVERIFY(!checker.canMoveTo(0, 5, White, 5, 5, cb));
}
Example #18
0
void Console::ShowChessboard(const ChessBoard& chessboard)
{
	int size = chessboard.GetSize();
    for(int y=-1; y<size; ++y)
    {
        for(int x=-1; x<size; ++x)
        {
            if(x == -1 && y == -1)
            {
                //cout << " ♨ ";
				cout << " x ";
				continue;
            }

            if(y == -1)
            {
                if(x < 10)
                    cout << " "<< x << " ";
                else if(x >= 10 && x < 100)
                    cout << x << " ";
                continue;
            }

            if(x == -1)
            {
                if(y < 10)
                    cout << " "<< y << " ";
                else if(y >= 10 && y < 100)
                    cout << y << " ";
                continue;
            }

            switch(chessboard.GetChess(x, y))
            {
                case CT_NULL:
                    //cout << " ┼ ";
					cout << "   ";
					break;
                case CT_WHITE:
                    //cout << " ☻ ";
					cout << " o ";
					break;
                case CT_BLACK:
                    //cout << " ☺ ";
					cout << " # ";
					break;
                default:
                    cout << "  ";
                    break;
            }
        }
        cout<<"\n";
    }
}
Example #19
0
//Make a move if it is valid
bool Piece::move(ChessBoard &board, int fromRow, int fromCol, int toRow, int toCol) {
	if(checkMove(board, fromRow, fromCol, toRow,toCol)) {
		board.getPiece(toRow, toCol)->setCaptured();
		board.swap(fromRow, fromCol, toRow, toCol);
		hasMoved = true;
		return true;
	} else {
		//Invalid move
		return false;
	}
}
Example #20
0
/*
JNIEXPORT jintArray JNICALL Java_jwtc_chess_JNI_getMoveArray(JNIEnv *env, jobject thiz)
{
	ChessBoard *board = stGame->getBoard();
	board->getMoves();
	int size = board->getNumMoves();
		
	 jintArray result;
	 result = env->NewIntArray(size);
	 if (result == NULL) {
		 return NULL; // out of memory error thrown
	 }
	 int i = 0;
	 // fill a temp structure to use to populate the java int array
	 jint fill[size];
	 
	 while(board->hasMoreMoves())
	 {
		fill[i++] = board->getNextMove(); 
	 }
	 // move from the temp structure to the java structure
	 env->SetIntArrayRegion(result, 0, size, fill);
	 return result;
}
*/
JNIEXPORT int JNICALL Java_jwtc_chess_JNI_getMoveArraySize( JNIEnv* env, jobject thiz)
{
    ChessBoard *board = stGame->getBoard();
    board->getMoves();
    //DEBUG_PRINT("W hasOO %d, hasOOO %d B hasOO %d, hasOOO %d | COL %d, %d", board->hasOO(1), board->hasOOO(1), board->hasOO(0), board->hasOOO(0), ChessBoard::COL_AROOK, ChessBoard::COL_HROOK);
    int i = 0;
    while(board->hasMoreMoves())
     {
            stArrMoves[i++] = board->getNextMove();
     }
    return board->getNumMoves();
}
void PgntestTest::PawnMoveChecker_canCaptureOnForwardDiagonal()
{
    ChessBoard cb;
    ChessBoardPiece piece;
    piece.color = Black;
    piece.type = Pawn;

    cb.setPiece(2, 1, piece);

    PawnMoveChecker checker;

    QVERIFY(checker.canMoveTo(1, 0, White, 2, 1, cb));
}
Example #22
0
void BaseMove::SelectMoveOne(ChessBoard & board, QPoint & pos, const int d_row, const int d_col, const int player)
{
    int col = pos.x() + d_col;
    int row = pos.y() + d_row;

    if (col >= 0 && row >= 0 && col < ChessBoard::MAX_ROWS && row < ChessBoard::MAX_ROWS) {
        if(board.IsFreeCell(row, col)) {
            board.SetSelectedCell(row, col, true);
        }
        else if(!board.IsMyPiece(row, col, player)) {
            board.SetSelectedCell(row, col, true);
        }
    }
}
Example #23
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    ChessBoard board;
    board.Initialise();
    QQmlApplicationEngine engine;

    QUrl appPath(QString("%1").arg(app.applicationDirPath()));
    engine.rootContext()->setContextProperty("appPath", appPath);
    engine.rootContext()->setContextProperty("chessModel", &board);

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}
Example #24
0
int main(int argc, char* argv[])
{
    QApplication a(argc, argv);
    ChessBoard w;
    ThemeDialog td;
    AboutDialog ad;
    RuleBook rb;

    themeEditor = &td;
    about = &ad;
    rules = &rb;

    w.show();
    return a.exec();
}
Example #25
0
////////////////////////////////////////////////////////////////////////////////
// search the hashkey database, randomly choose a move
////////////////////////////////////////////////////////////////////////////////
int Game::searchDB()
{
	if(DB_SIZE == 0 || DB_FP == NULL)
	{
		DEBUG_PRINT("No database search\n", 0);
		return 0;
	}
	if(m_board->getNumBoard() > Game::DB_DEPTH)
	{
		DEBUG_PRINT("Too many plies for database search\n", 0);
		return 0;
	}
	if(m_board->getFirstBoard()->getHashKey() != DEFAULT_START_HASH)
	{
		DEBUG_PRINT("Game not from default starting position (database search)\n", 0);
		return 0;
	}
	ChessBoard *tmpBoard = new ChessBoard();
	
	int moveArr[100], iCnt = 0, move; 
	//
	m_board->getMoves();
	while (m_board->hasMoreMoves() && iCnt < 100) 
	{
            move = m_board->getNextMove();
            m_board->makeMove(move, tmpBoard);
            const BITBOARD bb = tmpBoard->getHashKey();

            //DEBUG_PRINT("Trying to find %lld\n", bb);
            
            if(findDBKey(bb) < DB_SIZE){
                moveArr[iCnt++] = move;
            }
	}
	if(iCnt == 0)
	{
		DEBUG_PRINT("No move found in openingsdatabase\n", 0);
		return 0;
	}
	
	DEBUG_PRINT("Choosing from %d moves\n,", iCnt);
	
	timeval time;
	gettimeofday(&time, NULL);
	srand((unsigned int)time.tv_usec);
	int i = rand() % iCnt;
	return moveArr[i];
}
Example #26
0
void gmstart()
{
	board.Reset();
	Timer->Reset();
	hge->System_SetState(HGE_FRAMEFUNC, FrameFunc);
	hge->System_SetState(HGE_RENDERFUNC, RenderFunc);
}
void PgntestTest::FENForm_convertPoseToFen()
{
    ChessBoardPiece piece;
    piece.color = White;
    piece.type = None;
    ChessBoard cb;
    cb.setPiece(1, 4, piece);
    piece.color = White;
    piece.type = Pawn;
    cb.setPiece(3, 4, piece);

    FENForm fenForm;
    QString fenStr = fenForm.getFENForm(cb, White).c_str();

    QCOMPARE(fenStr, QString("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq -"));
}
Example #28
0
bool ChessMove::IsValidMoveRook(const ChessBoard& board) const{
    if (endX==startX){
        int deltaY = 1;
        if (startY > endY){deltaY = -1;}
        for (int i = startY+deltaY; GetCondition(i, startY, endY); i+=deltaY)
            if (board.GetPiece(startX, i)) return false;
        return true;
    } else if (endY==startY){
        int deltaX = 1;
        if (startX > endX){deltaX = -1;}
        for (int i = startX+deltaX; GetCondition(i, startX, endX); i+=deltaX)
            if (board.GetPiece(i, startY)) return false;
        return true;
    }
    return false;
}
Example #29
0
void rplystart()
{
	try
	{
		FileDlg ofn;
		ofn.SetFilter("存档文件(*.rply)\0*.rply\0\0");
		if(ofn.show())
		{
			replay.clear();
			rplypos = 0;
			fstream fs(ofn.GetFile(), ios::in | ios::binary);
			if(!fs) throw exception("录像文件打开失败!");
			while(!fs.eof())
			{
				char chr;
				fs>>chr;
				replay.push_back(chr);
			}
			fs.close();

			board.Reset();
			Timer->Reset();
			hge->System_SetState(HGE_FRAMEFUNC, FrameFunc2);
			hge->System_SetState(HGE_RENDERFUNC, RenderFunc2);
		}
	}
	catch(exception &ex)
	{
		MessageBoxA(0, ex.what(), 0, 0);
	}
}
Example #30
0
 //shows possible move location of where the piece could move to
 void King::showPossibleMoveLocation(ChessBoard& gameBoard)const{
     std::vector<sf::Vector2i> possibleLocation = getPossibleMoveLocation(gameBoard);
     for(int i = 0; i < possibleLocation.size(); ++i){
         const sf::Vector2i& vec = possibleLocation[i];
         gameBoard.makeHighlighted(vec.x, vec.y);
     }         
 }