Example #1
0
void KReversiView::setGame(KReversiGame *game)
{
    // disconnect signals from previous game if they exist,
    // we are not interested in them anymore
    if (m_game) {
        disconnect(m_game, SIGNAL(boardChanged()), this, SLOT(updateBoard()));
        disconnect(m_game, SIGNAL(moveFinished()), this, SLOT(gameMoveFinished()));
        disconnect(m_game, SIGNAL(gameOver()), this, SLOT(gameOver()));
        disconnect(m_game, SIGNAL(whitePlayerCantMove()), this, SLOT(whitePlayerCantMove()));
        disconnect(m_game, SIGNAL(blackPlayerCantMove()), this, SLOT(blackPlayerCantMove()));
        delete m_game;
    }

    m_game = game;

    if (m_game) {
        connect(m_game, SIGNAL(boardChanged()), this, SLOT(updateBoard()));
        connect(m_game, SIGNAL(moveFinished()), this, SLOT(gameMoveFinished()));
        connect(m_game, SIGNAL(gameOver()), this, SLOT(gameOver()));
        connect(m_game, SIGNAL(whitePlayerCantMove()), this, SLOT(whitePlayerCantMove()));
        connect(m_game, SIGNAL(blackPlayerCantMove()), this, SLOT(blackPlayerCantMove()));

        m_game->setDelay(m_delay);
    }

    m_hint = KReversiMove();

    updateBoard();
}
// Interprets the en passant move from the opponent.
void ChessBoard::en_passant_recognition(bool isWhite) {
	if (isWhite) {
		if (white_en_passant != 0) {
			if (final_pos_opponent == white_en_passant - 8 &&
				table->pieces[final_pos_opponent].name == 'p') {
			
				table->whiteLostPieces.push_back('P');
				table->whitePawns &= ~(1ULL << white_en_passant);
				table->whitePieces &= ~(1ULL << white_en_passant);
				table->occupied &= ~(1ULL << (white_en_passant));
				table->pieces[white_en_passant].name = EMPTY_CODE;
				table->pieces[white_en_passant].nextMoves = 0ULL;
				table->pieces[white_en_passant].nextAttacks = 0ULL;
				white_en_passant = 0;
				updateBoard();
			}
		}
	} else {
		if (black_en_passant != 0) {
			if (final_pos_opponent == black_en_passant + 8 &&
				table->pieces[final_pos_opponent].name == 'P') {
			
				table->blackLostPieces.push_back('p');
				table->blackPawns &= ~(1ULL << black_en_passant);
				table->blackPieces &= ~(1ULL << black_en_passant);
				table->occupied &= ~(1ULL << (black_en_passant));
				table->pieces[black_en_passant].name = EMPTY_CODE;
				table->pieces[black_en_passant].nextMoves = 0ULL;
				table->pieces[black_en_passant].nextAttacks = 0ULL;
				black_en_passant = 0;
				updateBoard();
			}
		}
	}
}
Example #3
0
// These two functions get called each time the game progresses
void progressGame( InputData inputdata )
{
    updatePosition( &(gamedata.curTm), inputdata.moveDir );
    updatePosition( &(gamedata.curTm), DOWN );
    rotateTetromino( &(gamedata.curTm), inputdata.shouldRotate );
    updateBoard( gamedata.curTm );
}
Example #4
0
void StatWidget::update() {
    NodeItem::m.lock();
    treeView->doItemsLayout();
    NodeItem::m.unlock();
    updateBoard();
    Ui_Statsui::depth->setText("Depth: " + QString::number(rb.depth));
    setWindowTitle(QString::fromStdString(rb.getInfo()).left(20) + QString::fromStdString(rb.getLine()));
    static QList<Stats> prev;
    prev.append(rb.getStats());
    if (prev.size() > 10)
        prev.removeFirst();

#define DISPLAYNUM(x) n##x->setText(number(prev.last().x)); if (prev.size() > 1) v##x->setText(number((prev.last().x - prev.first().x) / (prev.size()-1)));

    ninternalNode->setText(number(WorkThread::getRunning()));
//    vttentries->setText(stats.tt);
    DISPLAYNUM(node)
    DISPLAYNUM(eval)
    DISPLAYNUM(tthit)
    DISPLAYNUM(ttuse)
    DISPLAYNUM(ttalpha)
    DISPLAYNUM(ttbeta)
    DISPLAYNUM(ttoverwrite)
    DISPLAYNUM(ttinsufficient)
    DISPLAYNUM(ttstore)
    DISPLAYNUM(ttmerge)
    DISPLAYNUM(leafcut);
    DISPLAYNUM(pthit);
    DISPLAYNUM(ptmiss);
    DISPLAYNUM(ptuse);
    DISPLAYNUM(ptcollision);
    DISPLAYNUM(jobs);
    DISPLAYNUM(cancelJob); }
void *run(void *ptr_shared_data) {
	char cTmp[MAX_LINE];

	int l_change = 0;

	g_ptr_shared_data = (struct shared_data *) ptr_shared_data;
	// Initialize datarefs
	g_comFreq = g_ptr_shared_data->comFreq;

	last_mainloop_idle = sys_time_clock_get_time_usec();
	// while stop == 0 calculate position.
	while (g_ptr_shared_data->stop == 0) {
		long loop_start_time = sys_time_clock_get_time_usec();

		///////////////////////////////////////////////////////////////////////////
		/// CRITICAL FAST 20 Hz functions
		///////////////////////////////////////////////////////////////////////////
		if (us_run_every(50000, COUNTER3, loop_start_time)) {
			// read usb board values
			l_change = readDevice(&g_usb_data);
			// Update xplane
			updateHost();
			// Update board
			updateBoard();
		}
		///////////////////////////////////////////////////////////////////////////

		///////////////////////////////////////////////////////////////////////////
		/// NON-CRITICAL SLOW 10 Hz functions
		///////////////////////////////////////////////////////////////////////////
		else if (us_run_every(100000, COUNTER6, loop_start_time)) {
			//update_screen();
		}
		///////////////////////////////////////////////////////////////////////////

		if (loop_start_time - last_mainloop_idle >= 100000) {
			writeLog("CRITICAL WARNING! CPU LOAD TOO HIGH.\n");
			last_mainloop_idle = loop_start_time;//reset to prevent multiple messages
		} else {
			//writeConsole(0, 0, "CPU LOAD OK.");
		}

		// wait 1 milliseconds
#if IBM
		Sleep(1);
#endif
#if LIN
		usleep(10);
#endif
		g_counter++;
	}
	sprintf(cTmp, "thread closing usb device %d...\n", 0);
	writeLog(cTmp);
	closeDevice();
	sprintf(cTmp, "thread info : stopping thread #%d, %d!\n",
			g_ptr_shared_data->thread_id, g_counter);
	writeLog(cTmp);
	pthread_exit(NULL);
	return 0;
}
Example #6
0
void pdfBoard::zoomIN() {
  qDebug() << "ZoomIN" << zoom;
  if ( zoom >= 1 ) zoom ++;
  else if ( zoom > 0 ) zoom *= 2;
  else zoom = 0.1;
  updateBoard();
}
Example #7
0
void pdfBoard::zoomOUT() { 
  qDebug() << "ZoomOut:" << zoom;
  if ( zoom > 1 ) zoom --;
  else zoom /= 2;
  if ( zoom == 0 ) zoom = 0.1;
  updateBoard();
}
Example #8
0
void Game::recieveMove() {
	GAMESTATE res_flag;
	//sleep(1);
	MOVE mv = current->getMove();
	delete thread;
	// check move
	if (!board.move(mv)) {
		// wrong move - request move again
		//qDebug() << "(!) wrong move: " << mv.from.x+1 << "," << mv.from.y+1 << " >> " << mv.to.x+1 << "," << mv.to.y+1;
		move();
		return;
	}
	emit updateBoard();
	// check finish
	if (res_flag = board.isWin()) {
		finish(res_flag);
		return;
	}
	// continue game
	if (!board.canMove()) {
		// change current player
		setCurrentPlayer(current->getColor() == WHITE ? BLACK : WHITE);
	}
	// next move, please!
	move();
}
Example #9
0
/* ==================================================================== */
WdgSingle::WdgSingle(QWidget *parent, Game *g, PlayerColor myClr)
  : WdgGame(parent, g),
    botThinks(false)
{
    static size_t num = 1;
    static std::shared_ptr<Ai> ai_rand = std::make_shared<AiRandom>();

    setWindowTitle(QString("PvE #%1").arg(num++));

    emit updateBoard();

    PlayerColor botClr = PlayerColor::White == myClr
                       ? PlayerColor::Black
                       : PlayerColor::White;
    gamebot.reset(new Game_bot(g, botClr));
    gamebot->setAi(ai_rand);

    connect(this, SIGNAL(makingMove(Turn)),
            this, SLOT(onMakingMove(Turn)));
    connect(this, SIGNAL(gameEnded(PlayerColor)),
            this, SLOT(onGameEnded(PlayerColor)));

    if (g->pulls() == botClr) {
        botThinks = true;
        QTimer::singleShot(2000, this, SLOT(onBotThinkTimeout()));
Example #10
0
void KReversiView::blackPlayerCantMove()
{
    // TODO: use Computer, You and Opponent instead in message
    QMetaObject::invokeMethod(m_qml_root, "showPopup",
                              Q_ARG(QVariant,
                                    i18n("Black can not perform any move. It is white turn again.")));
    updateBoard();
}
Example #11
0
// These two functions get called only once to initialise game state and graphics
void initializeGame( )
{
    gamedata.level = 1;
    gamedata.score = 0;
    gamedata.speed = INITIAL_SPEED;
    gamedata.curTm = createTetromino( );
    gamedata.nxtTm = createTetromino( );
    updateBoard( gamedata.curTm );
}
Example #12
0
/* ==================================================================== */
void WdgSingle::onBotThinkTimeout()
{
    if (game->isEnd()) return;

    botThinks = !gamebot->think();
    if (botThinks) QMessageBox::warning(this, tr("AI Error"),
        tr("Nastala chyba, je AI na rade?"));
Example #13
0
/*Get Computer Move and Update Board*/
int getComputerMove(Game *game) {
    Move *move = getMinimaxMove(game, oppositeCol(getUserColorBit(game->settings)));
    int res;
    printf("%s", COMPUTER_MOVE);
    printMove(move);
    updateBoard(game, move);
    freeMove(move);
    res = gameOver(game, getUserColorBit(game->settings));
    return res;
}
Example #14
0
void KReversiView::slotHint()
{
    if (!m_game) {
        m_hint = KReversiMove();
        return;
    }

    m_hint = m_game->getHint();
    updateBoard();
}
Example #15
0
int sudokuBoard::update() {
  int InfoPtr[3] = {-1, -1, -1};  
  getUpdate(InfoPtr);
  
  cout << "\033[1;31mX:"<<InfoPtr[0]<<"  Y:"<<InfoPtr[1]<<"   Value:";
  cout<<InfoPtr[2]<<"\033[0m\n"<<endl;

  updateBoard(InfoPtr[0], InfoPtr[1], InfoPtr[2]);

  return 1;
}
Example #16
0
void MainWindow::on_noButton_clicked()
{
    ui->diceButton->setVisible(true);

    ui->yesButton->setVisible(false);
    ui->noButton->setVisible(false);
    ui->boardspace_label->setVisible(false);
    ui->boardspace_price_label->setVisible(false);

    updateBoard();
}
Example #17
0
/* ==================================================================== */
void WdgSingle::onMakingMove(Turn const &move)
{
    bool isMyMove = game->pulls() != gamebot->getAiColor();

    if (isMyMove && game->makeMove(move)) {
        emit updateBoard();

        botThinks = true;
        QTimer::singleShot(2000, this, SLOT(onBotThinkTimeout()));
Example #18
0
void GUI::sTurnNext()
{
    if(game == nullptr)
        return;

    if(!game->nextTurn()) {
        QMessageBox::warning(this, QGuiApplication::applicationDisplayName(),
                "No next turn available in history buffer");
    } else {
        updateBoard();
    }
}
Example #19
0
void kMancalaMain::historyShow(int currentRow) {
	if ( currentRow == -1 ) return; 

	_manageToolbarItems();

	if ( _historyListWidget->count() == 1 ) {
		_historyListWidget->setCurrentRow(-1);
		return;
	}

	qDebug("Restoring board ... to item: %d", currentRow);
	kMancalaHistoryItem *i = _historyListWidget->getState(currentRow);

	player **p = i->getPlayers();
	int currentPlayer = i->getPlayerOnTurn();

	_board = new board(i->getBoard());
	_players[0] = new player(p[0]);
	_players[1] = new player(p[1]);

	_controller->setCurrentPlayer(i->getPlayerOnTurn());

	emit playersUpdated(_players, currentPlayer);
	emit updateBoard(_board);

	emit clearGameOver();
	if ( !_controller->gameOn(_board) ) {
//		if ( _gameOver ) return;

		int winner = _controller->winner(_board);

		player *p_winner = NULL;
		qDebug("Winner is %d", winner);
		
		if ( winner != -1 )
			p_winner = _players[winner];


		qDebug("History Game Over");
		_guiBoard->play();
		qDebug("Emitting gameOver");
		emit gameOver(p_winner);
		stopGame();
		qDebug("historyShow done");
	} else {
		qDebug("Not game over ...");
		_gameOver = false;
		_gamePaused = false;
		pauseGame();
	}

}
Example #20
0
/* ==================================================================== */
void WdgReplay::onValueChanged(int index)
{
    if (!gamerep) return;

    gamerep->go(index - curTurn);

    curTurn = index;
    emit updateBoard();

    bool atEnd = index == ui.horizontalSlider->maximum();
    if (atEnd) emit ui.pushButton->setChecked(false);
Example #21
0
void GUI::sTurnSkip()
{
    if(game == nullptr)
        return;

    if(!game->skipTurn()) {
        QMessageBox::warning(this, QGuiApplication::applicationDisplayName(),
                "Can't skip current turn - at least one valid move is "
                "available");
    } else {
        updateBoard();
    }
}
Example #22
0
void gameLoop() { 
    int curPlayer = connA; //socket for the current player
    /*
     * Board represents the curent state of the pegs in the board
     * Each digit corresponds to the number of pegs in that digits row
     * i.e. Row 1 has 1 peg, row 2 has 3 pegs, etc.
     * 9 is prepended to ensure the number always has 5 digits, but is not used
     */
    int board = 91357;  
   while(1) {
        //send Board to player
        char c = 'B';
        write(curPlayer, &c, 1);
        char boardChar[6];
        sprintf(boardChar, "%d", board);
        int left = strlen(boardChar);
        int put = 0;
        int num;
        while (left > 0) {
        if ((num = write(curPlayer, boardChar + put, left)) < 0) {
            perror("nim_server:write");
            exit(0);
        } else {
            left -= num;
        }
        put += num;
        }
        c = ';';
        write(curPlayer, &c, 1);
        //Read player's move
        char buffer[3];
        c = '0';
        read(curPlayer, &c, 1); //Get Type
        if (c != 'M') {
            fprintf(stderr, "nim_match:invalid message type %c\n", c);
            winGame(switchPlayer(curPlayer));
        }
        read(curPlayer, buffer, 1); //read the move TODO: validate in case of network corruption
        read(curPlayer, buffer + 1, 1);
        read(curPlayer, &c, 1);
        if (c != ';') {
            fprintf(stderr, "nim_match:invalid move\n");
            winGame(switchPlayer(curPlayer));          
        }
        board = updateBoard(board, buffer);
        if (board == 90000) {
            winGame(switchPlayer(curPlayer));
        }
        curPlayer = switchPlayer(curPlayer);    
    }
}
Example #23
0
/*Determine whether given Move exposes King, if not - Move is valid*/
int isValidMove(Game *game, Move *move){
	int res = 0;
	Color col = getColFromLoc(game->board, move->source);
	col = oppositeCol(col);
	Game *copyG = (Game*)malloc(sizeof(Game));
	if (copyG== NULL) exitOnError("malloc");
	copyGame(game, copyG);
	updateBoard(copyG, move);
	if (!canKillKing(copyG, col)){
		res = 1;
	}
	free(copyG);
	return res;
}
Example #24
0
/*Build Minimax Tree of fixed depth via DFS*/
MinimaxNode *getMinimaxTreeFixedDepth(Game *game, int depth, Move *move, Color uCol) {
    MinimaxNode *curr = (MinimaxNode*)malloc(sizeof(MinimaxNode));
    if (curr == NULL) exitOnError("malloc");
    curr->game = (Game*)malloc(sizeof(Game));
    if (curr->game == NULL) exitOnError("malloc");
    struct ListNode *moves;
    int i = 0;
    curr->depth = depth;
    copyGame(game, curr->game);
    curr->sons = NULL;
    curr->sonsK = 0;
    if (move != NULL) {
        updateBoard(curr->game, move);
    }
    if (depth == 1) {
        curr->move = move;
    }
    else {
        freeMove(move);
        curr->move = NULL;
    }
    if (depth == game->difficulty) {
        return curr;
    }
    if ((depth % 2 == 0 && uCol == WHITE) || (depth % 2 == 1 && uCol == BLACK)) {
        moves = getMoves(curr->game, WHITE);
    }
    else {
        moves = getMoves(curr->game, BLACK);
    }
    int size = listSize(moves);
    curr->sonsK = size;
    if (!size) {
        free(moves);
        return curr;
    }
    else {
        curr->sons = (MinimaxNode**)malloc(sizeof(MinimaxNode)*size);
        if (curr->sons == NULL) exitOnError("malloc");
        struct ListNode *temp = moves;
        for (i = 0; i < size; i++) {
            Move* tMove = copyMove(temp->move);
            curr->sons[i] = getMinimaxTreeFixedDepth(curr->game, depth + 1, tMove, uCol);
            temp = temp->next;
        }
        freeList(moves);
    }
    return curr;
}
Example #25
0
void View_Board::init(Game *_game) {
	qDebug() << "View_Board::init(Game *_game) -> BEGIN";
	
	// model
	game = _game;
	board = &game->getBoard();
	end_flag = END_NONE;
	
	// signal to update model
	connect(game, SIGNAL(updateBoard()), SLOT(updateBoard()));
	// signal to finish game
	connect(game, SIGNAL(finishGame(GAMESTATE)), SLOT(finishGame(GAMESTATE)));
	
	// draw board wrapper
	setGeometry(10, 10, 450, 400);
	
	// events
	installEventFilter(this);
	
	// show board
	show();
	
	qDebug() << "View_Board::init(Game *_game) -> END";
}
Example #26
0
//--------------------------------------------------------------
void ofApp::draw(){
	ofBackground(ofColor::darkMagenta);

	for(int i = 0; i < background_size-1; i++){
		drawBackground(elapsedTimers[i]);
	}


	updateBoard();

	ofSetLineWidth(5);
	ofDrawLine(lineXPos, 0, lineXPos, 768);			//2 more lines more thickness

	gui.draw();
}
Example #27
0
void RandomizeThread::run()
{
    Random rand;

    while(true)
    {
        m_pBoard->m_mutex.lock();

        if(m_pBoard->m_stopRandom)
        {
            m_pBoard->m_mutex.unlock();
            break;
        }

        if(m_pBoard->m_vecSteps.size()>=(WuZiChessBoard::ROWS+1)*(WuZiChessBoard::ROWS+1))
        {
            m_pBoard->m_mutex.unlock();
            break;
        }

        int x = rand.getRandNum(WuZiChessBoard::ROWS+1);
        int y = rand.getRandNum(WuZiChessBoard::ROWS+1);

        if(m_pBoard->m_chessPieces[x][y]!=0)
        {
            m_pBoard->m_mutex.unlock();
            continue;
        }

        m_pBoard->m_chessPieces[x][y] = m_pBoard->m_turn;

        Step step(x, y);
        m_pBoard->m_vecSteps.push_back(step);
        m_pBoard->drawChessPiece(x, y);
        m_pBoard->m_turn *= -1;
        emit updateBoard();

        if(m_pBoard->checkFinished())
        {
            m_pBoard->m_mutex.unlock();
            break;
        }

        m_pBoard->m_mutex.unlock();

        SleepForMilliSeconds(300);
    }
}
bool batchUpdateForGroup(int rowNum1, int colNum1, int rowNum2, int colNum2){   // Eliminate all numbers from slot 2 in slot 1
    for(int k = 1; k < 10; ++k){
        if(board[rowNum2][colNum2][k] == 1 && board[rowNum1][colNum1][k] == 1){
            board[rowNum1][colNum1][k] = 0;
            --board[rowNum1][colNum1][0];
            if(board[rowNum1][colNum1][0] <= 0)
                return false;
        }
    }

    if(board[rowNum1][colNum1][0] == 1){
        if(!updateBoard(rowNum1, colNum1, findNumber(rowNum1, colNum1)))
            return false;
    }

    return true;
}
Example #29
0
void WuZiChessBoard::randomize()
{
    if(m_bFinished)
    {
        return;
    }

    m_stopRandom = false;

    if(m_pRandomThread==NULL)
    {
        m_pRandomThread = new RandomizeThread(this);
        connect(m_pRandomThread, SIGNAL(updateBoard()), this, SLOT(update()));
    }

    if(!m_pRandomThread->isRunning())
        m_pRandomThread->start();
}
Example #30
0
int main() {
		initscr();
		noecho();
		genBoard(board);
		int ch;
		timeout(100);
		while (1) {
			ch = getch();
			if (ch == 32) /* spacebar */
				usleep(5);
			else
                usleep(10000);

			updateBoard(board);
			drawBoard(board);
			usleep(UPDATELENGTH);
		}
		endwin();
		return 0;
}