bool SudokuBoard::initFromFile(string filepath)
{
	clearBoard();
	ifstream in(filepath);
	if(!in.good()){
		cout << "[ERROR] initFromFile: " << filepath << " does not exist\n";
		clearBoard();
		return false;
	}
	
	string rowStr;
	int row = 1;
	while(!in.eof()){
		in >> rowStr;
		if(rowStr.length() != 9){
			cout << "[ERROR] initFromFile: " << filepath << ":" << row << ": Invalid line length\n";
			clearBoard();
			return false;
		}
		for(int col = 1; col <= 9; col++){
			int x = rowStr[col-1]-'0';
			if(x < 0 || x > 9){
				cout << "[ERROR] initFromFile: " << filepath << ":" << row << ":" << col << ": Invalid character '" << rowStr[col-1] << "'\n";
				clearBoard();
				return false;
			}
			this->setSqr(row, col, x);
		}
		row++;
		if(row >= 10) break;
	}
	in.close();
	
	return true;
}
Beispiel #2
0
void GenericTetris::startGame()
{
    clearBoard();
    updateScore(0);
    updateLevel(1);
    newPiece();
}
Beispiel #3
0
Board::Board (unsigned fixedHandicap)
{
  static const Position D4  = { 3,  3},
                        Q16 = {15, 15},
                        D16 = { 3, 15},
                        Q4  = {15,  3},
                        D10 = { 3,  9},
                        Q10 = {15,  9},
                        K4  = { 9,  3},
                        K16 = { 9, 15},
                        K10 = { 9,  9};

  static std::vector<std::vector<Position>> handicap = {
    {D4, Q16},
    {D4, Q16, D16},
    {D4, Q16, D16, Q4},
    {D4, Q16, D16, Q4, K10},
    {D4, Q16, D16, Q4, D10, Q10},
    {D4, Q16, D16, Q4, D10, Q10, K10},
    {D4, Q16, D16, Q4, D10, Q10, K4, K16},
    {D4, Q16, D16, Q4, D10, Q10, K4, K16, K10}};

  assert(fixedHandicap >= 2);
  assert(fixedHandicap <= 9);

  clearBoard(state_);

  for (const Position& pos : handicap[fixedHandicap - 2])
  {
    state_[go::util::position2index(pos)] = PositionState::BLACK;
  }
}
void Draft::startDraft(Team *arr, vector<NodeData*>& a, int nTeams, WINDOW **board){
	int pickN, round = 0;
	srand(time(0));

	roundUp(++round, board[34]);

	while(round < 16){
		pickN = 0;

		for(int i = 0; i < nTeams; i++){
			if(arr[i].getUser()){
				pick(arr[i], a, board, pickN);
			}
			else if(!arr[i].getUser()){
				autoP(arr[i], a, board, pickN);
			}
			pickN++;
		}
		roundUp(++round, board[34]);
		for(int i = (nTeams - 1); i > -1; i--){
			if(arr[i].getUser())
				pick(arr[i], a, board, pickN);
			else if(!arr[i].getUser())
				autoP(arr[i], a, board, pickN);
			pickN++;
		}
		roundUp(++round, board[34]);
		clearBoard(board);
	}
}
Beispiel #5
0
Board::Board (const std::vector<Position>& freeHandicap)
{
  clearBoard(state_);
  for (const Position& pos : freeHandicap)
  {
    state_[go::util::position2index(pos)] = PositionState::BLACK;
  }
}
Beispiel #6
0
TicTacToe::TicTacToe(QWidget *parent, const char *name)
    : QWidget(parent, name)
{
    setCaption(tr("Tic-Tac-Toe"));
    clearBoard();
    if (qApp->isSessionRestored())
        restoreState();
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    boardWidget = new BoardViewer(this);
    ui->scrollArea->setWidget(boardWidget);

    connect(ui->nextMoveButtton,SIGNAL(clicked()),boardWidget,SLOT(nextMove()));
    connect(ui->clearButton,SIGNAL(clicked()),boardWidget,SLOT(clearBoard()));
    connect(ui->randomFillButton,SIGNAL(clicked()),boardWidget,SLOT(randomFill()));
    connect(ui->zoomInButton,SIGNAL(clicked()),boardWidget,SLOT(zoomIn()));
    connect(ui->zoomOutButton,SIGNAL(clicked()),boardWidget,SLOT(zoomOut()));
    connect(ui->sizeDownButton,SIGNAL(clicked()),boardWidget,SLOT(sizeDown()));
    connect(ui->sizeUpButton,SIGNAL(clicked()),boardWidget,SLOT(sizeUp()));
    connect(ui->cycledBorderButton,SIGNAL(toggled(bool)),boardWidget,SLOT(setBorderTypeCycled(bool)));
    connect(ui->deadBorderButton,SIGNAL(toggled(bool)),boardWidget,SLOT(setBorderTypeDead(bool)));
    connect(ui->mobiusBorderButton,SIGNAL(toggled(bool)),boardWidget,SLOT(setBorderTypeMobius(bool)));
    connect(ui->resetButton,SIGNAL(clicked()),boardWidget,SLOT(reset()));
    connect(ui->resetButton,SIGNAL(clicked()),this,SLOT(reset()));



    QSettings settings;
    int borderType=settings.value("/Settings/BorderType",GameBoard::borderCycled).toInt();
    switch (borderType)
    {
    case GameBoard::borderCycled: ui->cycledBorderButton->setChecked(true); break;
    case GameBoard::borderDead:   ui->deadBorderButton->setChecked(true); break;
    case GameBoard::borderMobius: ui->mobiusBorderButton->setChecked(true); break;
    }

    coords = new QLabel(this);
    generationNumber = new QLabel(this);
    generationNumber->setText(" "+tr("Покоління")+": 0");
    coords->setText("(-,-)");
    coords->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    coords->setMinimumWidth(coordLabelWidth);

    ui->statusBar->addWidget(coords);
    ui->statusBar->addWidget(generationNumber);

    connect(boardWidget,SIGNAL(changeGeneration(int)),this,SLOT(generationChanged(int)));
    connect(boardWidget,SIGNAL(changeCoords(QString,QString)),this,SLOT(coordsChanged(QString,QString)));

    ui->action_about->setShortcut(Qt::Key_F1);
    connect(ui->action_about,SIGNAL(triggered()),this,SLOT(aboutProgram()));
    connect(ui->action_Qt,SIGNAL(triggered()),this,SLOT(aboutQt()));

    ui->action_open->setShortcut(Qt::CTRL + Qt::Key_O);
    ui->action_save->setShortcut(Qt::CTRL + Qt::Key_S);
    connect(ui->action_open,SIGNAL(triggered()),this,SLOT(loadFromFile()));
    connect(ui->action_save,SIGNAL(triggered()),this,SLOT(saveToFile()));
}
//! [0]
TetrixBoard::TetrixBoard(QWidget *parent)
    : QFrame(parent)
{
    setFrameStyle(QFrame::Panel | QFrame::Sunken);
    setFocusPolicy(Qt::StrongFocus);
    isStarted = false;
    isPaused = false;
    clearBoard();

    nextPiece.setRandomShape();
}
Beispiel #9
0
void reset() {
   int i;
   choice = 0;
   clearBoard();
   for (i = 0; i < 26; i++) {
      avail[i] = 'a' + i;
      used[i] = 0;
      inword[i] = 0;
   }
   bad_guesses = 0;
   num_bad = 0;
   num_chars = 0;
   num_good = 0;
}
Beispiel #10
0
void GenericTetrix::startGame(int gameType,int fillRandomLines)
{
    gameID             = gameType;
    clearBoard(fillRandomLines);
    nLinesRemoved      = 0;
    updateRemoved(nLinesRemoved);
    nClearLines        = height;
    nPiecesDropped     = 0;
    score              = 0;
    updateScore(score);
    level              = 1;
    updateLevel(level);
    newPiece();
}
//initialize the board
void BogglePlayer::setBoard(unsigned int rows, unsigned int cols, string** diceArray)
{
    if (isBoardSet) {
        clearBoard();
    }
    mRows = rows;
    mCols = cols;
    
    //use a linear vector to represent the matrix
    for (int i = 0; i < mRows; i++) {
        for (int j = 0; j < mCols; j++) {
            board.push_back(toLowercase(diceArray[i][j]));
            isUsed.push_back(false);
        }
    }
    isBoardSet = true;
}
//! [4]
void TetrixBoard::start()
{
    if (isPaused)
        return;

    isStarted = true;
    isWaitingAfterLine = false;
    numLinesRemoved = 0;
    numPiecesDropped = 0;
    score = 0;
    level = 1;
    clearBoard();

    emit linesRemovedChanged(numLinesRemoved);
    emit scoreChanged(score);
    emit levelChanged(level);

    newPiece();
    timer.start(timeoutTime(), this);
}
GameAlgorithm::GameAlgorithm(int nDim)
	:	m_nSideLen(nDim)
	,	m_nScore(0)
    ,   m_mt19937((unsigned long)QDateTime::currentMSecsSinceEpoch())
{
	clearBoard();

	Point2DArr freeSlots;

	for (int row = 0; row < m_nSideLen; row++)
	{
		for (int col = 0; col < m_nSideLen; col++)
		{
			m_board[row][col] = NULL;
			Point2D p2d(row, col, NULL);
			freeSlots.push_back(p2d);
		}
	}

    putNextNumbersOnBoard(2 * (m_nSideLen / 4) * (m_nSideLen / 4), freeSlots);
}
Beispiel #14
0
void TicTacToe::mousePressEvent(QMouseEvent *event)
{
    if (turnNumber == 9) {
        clearBoard();
        update();
    } else {
        for (int position = 0; position < 9; ++position) {
            QRect cell = cellRect(position / 3, position % 3);
            if (cell.contains(event->pos())) {
                if (myState.at(position) == Empty) {
                    if (turnNumber % 2 == 0)
                        myState.replace(position, 1, Cross);
                    else
                        myState.replace(position, 1, Nought);
                    ++turnNumber;
                    update();
                }
            }
        }
    }
}
Beispiel #15
0
void Pony48Engine::resetBoard()
{
	clearBoard();
	
	//Start with 2 random tiles
	for(int start = 0; start < 2; start++)
	{
		while(true)
		{
			int x = randInt(0, BOARD_WIDTH-1);
			int y = randInt(0, BOARD_HEIGHT-1);
			if(m_Board[x][y] != NULL) continue;
			m_Board[x][y] = loadTile("res/tiles/2.xml");
			break;
		}
	}
	m_iScore = 0;	//Reset score also
	m_highestTile = NULL;
	m_fLastMovedSec = getSeconds();
	m_bHasBoredVox = false;
}
void GameAlgorithm::deserializeFromString(const QString strImage)
{
	QStringList lstImage = strImage.split(" ");

	if (lstImage.size() > 1)
	{
		bool bOk = false;
		int nSideLen = lstImage[0].toInt(&bOk);

		if (bOk && ((nSideLen == 4) || (nSideLen == 8) || (nSideLen == 16)))
		{
			if ((lstImage.size() - 1) == (nSideLen * nSideLen))
			{
				m_nSideLen = nSideLen;
				clearBoard();

				for (int row = 0; row < m_nSideLen; row++)
				{
					for (int col = 0; col < m_nSideLen; col++)
					{
						bool bOk = false;
						int nValue = lstImage[1+ (m_nSideLen * row + col)].toInt(&bOk);

						if (bOk)
						{
							m_board[row][col] = (unsigned int)(nValue);
							m_board[row][col].m = false;
							m_board[row][col].n = false;
							m_board[row][col].ids.clear();
							if (m_board[row][col] != ZERO)
								m_board[row][col].ids.push_back(row * m_nSideLen + col);
						}
					}
				}
			}
		}
	}
}
Beispiel #17
0
int Solver::completeBoard() {
    std::vector<int> nums = {
        UPPER_LEFT,
        UPPER_MID,
        MID_LEFT,
        UPPER_RIGHT,
        MID_MID,
        BOT_LEFT,
        MID_RIGHT,
        BOT_MID,
        BOT_RIGHT};
    int unsolvableBoardsCount = 0;
    int unsolvedThreshold = 30;

    for(auto n = nums.begin(); n != nums.end(); n++) {
        if(*n != seed1 && *n != seed2) {
            if(!solve(*n)) {
                unsolvableBoardsCount++;
                if(unsolvableBoardsCount == unsolvedThreshold) {
                    clearBoard();
                    unsolvedThreshold *= 2;
                    n = nums.begin();
                }
                else {
                    n--;
                    if(*n < 0) {
                        std::cout << "Error: No solution" << std::endl;
                        break;
                    }
                    sudokuBoard[*n].resetBoard();
                    n--;
                }
            }
        }
    }
    return unsolvableBoardsCount;
}
Beispiel #18
0
Board::Board() {
    clearBoard();
}
Beispiel #19
0
int main(int argc, char* argv[])
{
    //make window
    if(!init())
    {
        cout<<"Init failed";
    }
    
    //loads buttons and sprites
    loadMedia();
    
    bool quit=false;
    
    int menubutton=0;
    
    SDL_Event e;
    
    
    while(quit!=true)
    {
        while(SDL_PollEvent(&e)!=0)
        {
            //quits game
            if(e.type==SDL_QUIT)
            {
                quit=true;
            }
            
            //clears board during game
            if(e.key.keysym.sym==SDLK_SPACE)
            {
                clearBoard();
            }
            
            //returns to menu
            if(e.key.keysym.sym==SDLK_ESCAPE)
            {
                if(startgame==true)
                {
                    gamecontinue=true;
                }
                startgame=false;
                aboutstate=false;
            }

            //click during game to play
            if(e.type==SDL_MOUSEBUTTONDOWN && startgame==true)
            {
                if(checkGameOver()==true)
                {
                    clearBoard();
                }
                
                else
                {
                    SDL_GetMouseState( &x, &y );
                    
                    tile=whichButton(x,y);
                }
            }
            
            //click either start or about
            if(e.type==SDL_MOUSEBUTTONDOWN && startgame==false)
            {
                SDL_GetMouseState( &x, &y );
                
                menubutton=whichButton(x,y);
                
                if(menubutton==0)
                {
                    startgame=true;
                }
                else if(menubutton==1)
                {
                    aboutstate=true;
                }
                
            }
        }
        
        if(startgame==false && aboutstate==false)
        {
            menu();
        }
        
        else if(startgame==false && aboutstate==true)
        {
            about();
        }
        
        else if(startgame==true && aboutstate==false)
        {
            SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
            SDL_RenderClear(gRenderer);
            
            play();
            drawboard();

            if(checkGameOver()==true)
            {
                announceWinner();
            }
            
        }

        SDL_RenderPresent(gRenderer);
        
        SDL_Delay(100);
        
    }
    
    close();
    
    return 0;
}
Beispiel #20
0
void Board::resetBoard(QSize dim) {
	clearBoard();
	setupBoard(dim);
}
Beispiel #21
0
int QGtp::openGtpSession(QString path, QString args, int size, float komi, int handicap)
{
	_cpt = 1000;
	
	programProcess = new QProcess();
    programProcess->setReadChannel(QProcess::StandardOutput);
    QStringList arguments = args.split(' ',QString::SkipEmptyParts);
    issueCmdNb = false;

    if (path.contains(QRegExp("gnugo$", Qt::CaseInsensitive)))
        issueCmdNb = true; // FIXME: are command numbers really gnugo-specific?

	connect(programProcess, SIGNAL(readyRead()),
		this, SLOT(slot_readFromStdout()) );
	connect(programProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
		this, SLOT(slot_processExited(int , QProcess::ExitStatus )) );
	
    qDebug() << "QGtp::openGtpSession(" << path << "," << args << ")";

    programProcess->start(path, arguments);
	

	if (!programProcess->waitForStarted())
	{
          _response="Could not start "+path;
		  return FAIL ;
	}
	
	//?? never know ... otherwise, I get a segfault with sprint ...
	if ((outFile = (char *)malloc (100)) == NULL)
	{
		  _response="Yuck ! Could not allocate 100 bytes !!!"  ;
		  return FAIL ;
	}   
	
	if (protocolVersion()==OK)
	{
		if(getLastMessage().toInt() !=2)
		{
			qDebug("Protocol version problem???");
			//				quit();
			_response="Protocol version not supported";
			//				return FAIL;
		}
		if(setBoardsize(size)==FAIL)
		{
			return FAIL;
		}
		if(clearBoard()==FAIL)
		{
			// removed by frosla -> protocol changes...
			// return FAIL;
		}

/*
		if(knownCommand("level")==FAIL)
		{
			  return FAIL;
		}
	
		else if (getLastMessage().contains("true"))
        	{
        		if (setLevel(level)==FAIL)
			{
				return FAIL;
			}
        	}
*/ 
      
		if(setKomi(komi)==FAIL)
		{
			return FAIL;
		}

		if(fixedHandicap(handicap)==FAIL)
		{
			return FAIL;
		}
	}
	else
	{
		quit();
		_response="Protocol version error";
		return FAIL;
	}

    busy = false;
	return OK;
}
Beispiel #22
0
void PocketCivMain::generateNewBoard(BoardModel *boardModel)
{
    assert(boardModel != NULL);

    if(this->boardModel != NULL)
    {
        delete this->boardModel;
    }

    this->boardModel = boardModel;
    int width = this->boardModel->getWidth();
    int height = this->boardModel->getHeight();
    double sceneWidth = 37.5*double(width);
    double sceneHeight = 50.0*double(height);

    if(this->graphicsScene != NULL)
    {
        this->graphicsScene->deleteLater();
    }

    this->graphicsScene = new QGraphicsScene(0,0,sceneWidth,sceneHeight, this);

    if(this->graphicsView != NULL)
    {
        this->graphicsView->deleteLater();
    }
    this->graphicsView = new QGraphicsView(this->graphicsScene, this);
    this->setCentralWidget(this->graphicsView);

    this->clearBoard();

    for(int i = 0; i < width; ++i)
    {
        this->hexItems.append(QList<HexItem *>());
        for(int j = 0; j < height; ++j)
        {
            this->hexItems[i].append(NULL);
        }
    }

    if(this->boardBackground != NULL)
    {
        delete this->boardBackground;
    }

    this->boardBackground = new QGraphicsRectItem(HexItem::BOARD_BORDER-1, HexItem::BOARD_BORDER-1, HexItem::BOARD_BORDER+width*34-14, HexItem::BOARD_BORDER+height*40-7);
    this->boardBackground->setPen(QPen(QColor(0xb1,0xb1,0xb1)));
    this->boardBackground->setBrush(QBrush(QColor(0xb1,0xb1,0xb1)));
    this->graphicsScene->addItem(this->boardBackground);

    int x = 0;
    int y = 0;
    for(int i = 1; i <= width; i=i+2)
    {
        y = 0;
        for(int j = 1; j <= height; ++j)
        {
            HexModel *hexModel = this->boardModel->refHexModel(x,y);
            connect(hexModel, SIGNAL(hexModelUpdated(int, int)), this, SLOT(updateHex(int,int)));
            HexItem *hexItem = new HexItem(i*34-34,j*40-20, hexModel);
            this->graphicsScene->addItem(hexItem);
            this->hexItems[x][y] = hexItem;
            connect(hexModel, SIGNAL(hexTriggered(Qt::MouseButton,int,int)), this, SLOT(hexTriggerAction(Qt::MouseButton,int,int)));
            y++;
        }
        x = x + 2;
    }

    x = 1;
    for(int i = 1; i <= width; i=i+2)
    {
        y = 0;
        for(int j = 1; j <= height; ++j)
        {
            HexModel *hexModel = this->boardModel->refHexModel(x,y);
            connect(hexModel, SIGNAL(hexModelUpdated(int, int)), this, SLOT(updateHex(int,int)));
            HexItem *hexItem = new HexItem(i*34,j*40-40, hexModel);
            this->graphicsScene->addItem(hexItem);
            this->hexItems[x][y] = hexItem;
            connect(hexModel, SIGNAL(hexTriggered(Qt::MouseButton,int,int)), this, SLOT(hexTriggerAction(Qt::MouseButton,int,int)));
            y++;
        }
        x = x + 2;
    }

    connect(this->boardModel, SIGNAL(boardUpdated()), this, SLOT(updateBoard()));
    connect(this->boardModel, SIGNAL(boardCleared()), this, SLOT(clearBoard()));
    connect(this->boardModel, SIGNAL(sendMessage(const QString &)), this, SLOT(addMessage(const QString &)));
    connect(this->boardModel, SIGNAL(clearMessages()), this, SLOT(clearMessages()));
    connect(this->boardModel, SIGNAL(sendCardsLeftCount(int)), this, SLOT(setEventCardsLeft(int)));
    connect(this->boardModel, SIGNAL(sendDoneText(const QString &)), this, SLOT(setDoneText(const QString &)));
    connect(this->boardModel, SIGNAL(sendDialogClosed()), this, SLOT(continueWithPreviousInstruction()));
    connect(this->boardModel, SIGNAL(eraChanged(int)), this, SLOT(setEra(int)));
    connect(this->boardModel, SIGNAL(goldChanged(int)), this, SLOT(setGoldCount(int)));
    connect(this->boardModel, SIGNAL(gloryScoreChanged(int)), this, SLOT(setGloryCount(int)));

    if(this->overviewDialog)
    {
        this->overviewDialog->deleteLater();
    }
    this->overviewDialog = new OverviewDialog(this->boardModel, this);

    if(this->instruction != NULL)
    {
        this->instruction->deleteLater();
    }

    this->instruction = new NoInstruction();
    this->updateBoard();
}
Beispiel #23
0
//main
int main() {
  REG_DISPCNT = MODE_3 | BG2_ENABLE;

  enum GBAState state = START;
  enum GBAState prevState = state;

  while(1) {
		waitForVblank();
		switch(state) {
		case START:
			drawImage3(0,0,SPLASH_WIDTH,SPLASH_HEIGHT,splash);
			prevState = START;
			state = NODRAW;
			break;
		case NODRAW:

			if (prevState == START) {
				if (KEY_DOWN_NOW(BUTTON_START)) {
					state = GAME;
				}
				if (KEY_DOWN_NOW(BUTTON_A)) {
					state = HELP;
				}
			}
			if (prevState == HELP) {
				if (KEY_DOWN_NOW(BUTTON_SELECT)) {
					state = START;
				}
			}
			if (prevState == GAMEOVER) {
				if (KEY_DOWN_NOW(BUTTON_SELECT)) {
					state = START;
				}
			}

			break;
		case GAME:
			drawImage3(0,0,GAME2_WIDTH,GAME2_HEIGHT,game2);

			char stuff[4] = "000\0";
		  stuff[0] = 48 + (clearedRows/100)%10;
		  stuff[1] = 48 + (clearedRows/10)%10;
		  stuff[2] = 48 + clearedRows%10;
		  drawImagePartial(25, 180, 20, 30, GAME2_WIDTH, game2);
		  drawString(25,180,stuff, WHITE);

      block curr = randomBlock();
			block next = randomBlock();
      drawBlock(curr);
			int button = 0;
      while(1) {
				delay(20);
        if (KEY_DOWN_NOW(BUTTON_SELECT)) {
					prevState = GAME;
					state = START;
          break;
        }

        block old = curr;
        tick++;
        if (collisionDetectBottom(curr) == 1) {
          rowCheck(curr);
					curr = next;
					next = randomBlock();
					if(collisionDetect(curr) == 1) {
						prevState = GAME;
						state = GAMEOVER;
						break;
					}
        } else {
          if(KEY_DOWN_NOW(BUTTON_LEFT) && collisionDetectLeft(curr) == 0){
              curr.x--;
          } else if(KEY_DOWN_NOW(BUTTON_RIGHT) && collisionDetectRight(curr) == 0){
              curr.x++;
          } else if(KEY_DOWN_NOW(BUTTON_DOWN) && collisionDetectBottom(curr) == 0){
              curr.y--;
          } else if(button == 0 && KEY_DOWN_NOW(BUTTON_UP) && rotationDetect(curr) == 0){
							button = 1;
              rotateBlock(&curr);
          } else if (tick > 20) {
            tick = 0;
            curr.y--;
          } else if (!KEY_DOWN_NOW(BUTTON_DOWN)){
						//drawString(25,70,"stuff stuff", WHITE);
						button = 0;
					}
          waitForVblank();
          eraseBlock(old);
          drawBlock(curr);
        }
      }
      clearBoard();
      drawRect(4,4,70,10, BLACK);
			break;
		case GAMEOVER:
      drawImage3(0,0,END_WIDTH,END_HEIGHT,end);
			prevState = GAMEOVER;
			state = NODRAW;
			break;
		case HELP:
			drawImage3(0,0,HELP_WIDTH,HELP_HEIGHT,help);
			prevState = HELP;
			state = NODRAW;
			break;
		}
	}

  return 0;
}
Beispiel #24
0
OurBoard::OurBoard()
{
    clearBoard();
}
Beispiel #25
0
int main(int argc, char* args[])
{
	Screen screen = {};
	screen.width = SQUARE_DIM*SCALE*COLUMNS;
	screen.height = SQUARE_DIM*SCALE*ROWS;
	
	//init everything (window, main surface, renderer, SDL_Image)
	//NOTE: This is probably a bad way to do this since I am changing data inside function instead of returning something
	if(!init(&screen))
	{
		printf("Something could not be initialized! Error: %s\n", SDL_GetError());
	}

	//set Texture class render pointer
	Texture::setRenderer(screen.renderer);

	//set Square's main texture
	Square::setTexture("tiles.png");

	//create a blockbuilder
	BlockBuilder builder;

	//get a block pointer
	Block* block = null;

	//create an array for the Tetris board that will hold all inanimate squares
	Board board = {0};
	//int numGrid = ROWS*COLUMNS;
	//Square board_squares[ROWS*COLUMNS];
	
	//set up locations for board squares
	board.numSquares = COLUMNS*ROWS;	
	for(int i = 0; i < board.numSquares; ++i)
	{
		int x = (i%COLUMNS)*SQUARE_DIM*SCALE;
		int y = (i/COLUMNS)*SQUARE_DIM*SCALE;

		board.squares[i].setX(x);
		board.squares[i].setY(y);
		board.squares[i].concrete = 0;
	}

	//create vector for blocks
	//std::vector<Block*> blocks;
	//blocks.push_back(builder.buildBlock(L_BLOCK, RED, 0, 0));

	bool quit = false;
	SDL_Event event;
	
	//timer variables
	uint32 currentTime = SDL_GetTicks();
	uint32 previousTime = 0;

	//init RNG
	srand(time(0));

	Color colors[4];
	colors[0] = RED;
	colors[1] = BLUE;
	colors[2] = GREEN;
	colors[3] = YELLOW;

	BlockType blockTypes[5];

	blockTypes[0] = T_BLOCK;
	blockTypes[1] = I_BLOCK;
	blockTypes[2] = O_BLOCK;
	blockTypes[3] = S_BLOCK;
	blockTypes[4] = L_BLOCK;

	while(!quit)
	{
		//check to see if there is no active block
		if(!block)
		{
			int color = rand()%4;
			int blockType = rand()%5;
			block = builder.buildBlock(blockTypes[blockType], colors[color], 210, 30);
			block->setLowestPoint(board.blocksInColumn);
			//block->setLowestBlockY();
		}

		while(SDL_PollEvent(&event))
		{
			if(event.type == SDL_QUIT)
			{
				quit = true;
				printf("QUITTING! Another successful run! :)\n");
			}	
			else if(event.type == SDL_KEYDOWN)
			{
				switch(event.key.keysym.sym)
				{
					case SDLK_UP:
					{
						//rotate block counter - clockwise
						block->rotateBlock(board.squares, board.blocksInColumn, -1);
					} break;

					case SDLK_DOWN:
					{
					} break;

					case SDLK_RIGHT:
					{
						block->moveBlock(VELOCITY, board.squares, board.blocksInColumn);
					} break;

					case SDLK_LEFT:
					{
						block->moveBlock(-VELOCITY, board.squares, board.blocksInColumn);
					} break;
					case SDLK_SPACE:
					{
						//first set block's squares to resting place height
						block->setToRest();
					} break;

					default:
					{
					}
				}
			
			}
			
		}
		
		//clear screen set to light gray	
		SDL_SetRenderDrawColor(screen.renderer, 0, 0, 0, 0);
		SDL_RenderClear(screen.renderer);
	
		//render the grid
		renderGrid(screen.renderer);
		//the block
		block->render();	
		//printf("Final Y: %d, LowY: %d\n", block->finalY, block->blockLowY);
		//render board
		for(int i = 0; i < board.numSquares; ++i)
		{
			if(!board.squares[i].concrete) //check if null
			{
				continue;
			}
			board.squares[i].renderBoardSquare();
		}

		//printf("x: %d y: %d\n", block->getX(), block->getY());
		SDL_RenderPresent(screen.renderer);
		
		//bool makeStatic = false; // has block reached its final resting place?

		//check to see if 1/2 of a second has passed. 
		//if so, update locationsj
 		currentTime = SDL_GetTicks();	
		if((currentTime - previousTime) > 500)
		{
			//printf("currentTime - previousTime = %d\n", currentTime - previousTime);
			//updateBlocks(&blocks, board_squares);
			if(updateBlocks(block, &board))
			{
				block = null;

				//check to see if any rows are full
				FilledRowRegion check = checkBoard(&board);

				if(check.firstFilledRow > -1) //then there is a row that is filled!
				{
					clearBoard(check.firstFilledRow, check.lastFilledRow, &board);
				}
			}
			previousTime = currentTime;
		}
		
	}
	
	SDL_DestroyRenderer(screen.renderer);
	SDL_DestroyWindow(screen.window);
	screen.window = null;

	SDL_Quit();
	IMG_Quit();
	return 0;
}
BoardController::BoardController(QObject *parent) :
    QObject(parent) ,
    m_logic_controller(*this)
{
    clearBoard();
}
Beispiel #27
0
void Board_start()
{
	int experimentEndTime;
	int updateFlag;
	int quitFlag;
	Board b;
	BoardThreadParams threadParams[MAX_N_ROBOTS];
	BoardDatabase *db;

#ifdef IS_WIN
	CvSize szGlobal = {ENVIR_DIMS, ENVIR_DIMS};
	CvSize szLocal = {LOC_MAP_DIMS, LOC_MAP_DIMS};
	IplImage *globMapIplImage;
	IplImage *localMapIplImage;
#endif

	setupExperimentDir();

	// Do this before setting up the database
	SET_N_ROBOTS(1)
#ifdef SETUP_TEST_COALITION
	SET_N_ROBOTS(2)
	SET_N_ROBOTS_THREADS_FOR_TEST_COAL(1)
#endif

#ifdef IS_WIN
	globMapIplImage = cvCreateImage (szGlobal, 8, 1);
	localMapIplImage = cvCreateImage (szLocal, 8, 1);
	b = initBoard (globMapIplImage, localMapIplImage);
#else
	b = initBoard();
#endif
	db = &b.db;

#ifdef SETUP_TEST_COALITION
	Board_setupTestCoalRobots (&b.db);
#endif

#ifdef SHOW_IMGS
	Visualisation_showSim (db);
	Visualisation_showMap (db);
//	printf ("Adjust windows and click to start\n"); cvWaitKey (0);
#endif

	if (-1 == setupSockets (db, threadParams))
	{
		goto cleanupBoard;
	}

	experimentEndTime = clock() + 10000;
	printf ("Experiment ends at %d.\n", experimentEndTime);

	if (-1 == setupThreads (db, threadParams))
	{
		goto cleanupBoard;
	}

	printf ("All threads started. Entering blackboard server loop.\n");

	quitFlag = 0;
	while (!quitFlag)
	{
		enterBoardData();
		checkTime (db, experimentEndTime, &updateFlag);
		if (updateFlag)
		{
			Board_processData (&b, 1);

			//! \todo Allocate coalitions

			quitFlag = checkIfAllFinished (db);
		}
		leaveBoardData();

		if (!updateFlag)
		{
			SLEEP_FOR_MS(10)
		}
	}

	printf ("Finished loop. Closing sockets.\n");

	closeSockets (db);

	Board_finish (&b);

cleanupBoard:
	clearBoard (&b);
#ifdef IS_WIN
	cvReleaseImage (&globMapIplImage);
	cvReleaseImage (&localMapIplImage);
	cvCleanup();
#endif
}
Beispiel #28
0
/**
 * function that refresh the scene
 */
void GameBoard::refresh() {
    //qDebug() << "gameboard refreshed";
    QList<QPair<uint, uint> >list;
    QString debug_str;
    QPointF point;
    QList<QPair<int,int> > pos_moves;
    clearBoard();
    /** if some possible moves is showed , hide them... */
    if (possible_moves.count() != 0)
        hidePossibleMoves();


    /** if the move is valid */
    if (game->getError().isEmpty()) {
        /** check if some possible moves are on the core board */
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (game->board[i][j] == Game::MEN_POSSIBLE_MOVE) {
                    pos_moves.append(QPair<int,int>(i,j));
                }
            }
        }
        /** if there are some possible moves */
        if (pos_moves.count() != 0) {
            /** ligthen them up and set timer on darkening */
            lightenPossibleMoves(pos_moves);
            QTimer::singleShot(2500, this, SLOT(toutExpired()));
        }
        /** pass the entire board */
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
               /** light rock detected */
                if (game->board[i][j] == Game::MEN_WHITE) {
                    debug_str += "white rock\t";
                    LightRock * light = new LightRock();
                    light_rocks.append(light);
                    point = this->convertCoords(j,i);
                    canvas->addItem(light);
                    light->setPos(67.5 + point.x(), 67.5 + point.y());

                }
                /** dark rock detected */
                else if (game->board[i][j] == Game::MEN_BLACK) {
                    debug_str += "black rock\t";
                    DarkRock * dark = new DarkRock();
                    dark_rocks.append(dark);
                    point = this->convertCoords(j,i);
                    canvas->addItem(dark);
                    dark->setPos(67.5 + point.x(), 67.5 + point.y());
                }
                /** light king */
                else if (game->board[i][j] == Game::MEN_WHITE_KING) {
                    debug_str += "white king\t";
                    LightRock * light = new LightRock();
                    light_rocks.append(light);
                    point = this->convertCoords(j,i);
                    canvas->addItem(light);
                    light->setPos(67.5 + point.x(), 67.5 + point.y());
                    light->becomeKing();

                }
                /** dark king */
                else if (game->board[i][j] == Game::MEN_BLACK_KING) {
                    debug_str += "black king\t";
                    DarkRock * dark = new DarkRock();
                    dark_rocks.append(dark);
                    point = this->convertCoords(j,i);
                    canvas->addItem(dark);
                    dark->setPos(67.5 + point.x(), 67.5 + point.y());
                    dark->becomeKing();
                }
                /** possible moves are already processed */
                else if (game->board[i][j] == Game::MEN_POSSIBLE_MOVE) {
                    debug_str += "possible move\t";
                }
                else {
                    debug_str += "nothing\t";
                }
            }
            //qDebug() << debug_str;
            debug_str = "";
        }
        /** set content of moves notification area */
        lineedit_moves = game->getIcpSyntaxStr(false);
        MainWindow::getInstance()->setLineEditText(lineedit_moves);
    }
}
Beispiel #29
0
int QGtp::openGtpSession(QString filename, int size, float komi, int handicap, int /*level*/)
{
	_cpt = 1000;
	
	programProcess = new QProcess();
    programProcess->setReadChannel(QProcess::StandardOutput);
	QStringList arguments;
	issueCmdNb = false;
	
	if(!filename.count())
	{
		_response = "No go engine path set";
		return FAIL;
	}

	if (filename.toLower().contains("gnugo"))
	{
		arguments << "--mode" << "gtp" << "--quiet" ;
		issueCmdNb = true;
	}

	if (filename.toLower().contains("mogo"))
	{
		arguments << "--19" << "--dontDisplay" << "1" ;

	}


	connect(programProcess, SIGNAL(readyRead()),
		this, SLOT(slot_readFromStdout()) );
	connect(programProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
		this, SLOT(slot_processExited(int , QProcess::ExitStatus )) );
	
    qDebug("starting Go engine : %s %s", filename.toLatin1().constData(), arguments.join(" ").toLatin1().constData());

	programProcess->start(filename, arguments);

	

	if (!programProcess->waitForStarted())
	{
		  _response="Could not start "+filename;
		  return FAIL ;
	}
	
	//?? never know ... otherwise, I get a segfault with sprint ...
	if ((outFile = (char *)malloc (100)) == NULL)
	{
		  _response="Yuck ! Could not allocate 100 bytes !!!"  ;
		  return FAIL ;
	}   
	
	if (protocolVersion()==OK)
	{
		if(getLastMessage().toInt() !=2)
		{
			qDebug("Protocol version problem???");
			//				quit();
			_response="Protocol version not supported";
			//				return FAIL;
		}
		if(setBoardsize(size)==FAIL)
		{
			return FAIL;
		}
		if(clearBoard()==FAIL)
		{
			// removed by frosla -> protocol changes...
			// return FAIL;
		}

/*
		if(knownCommand("level")==FAIL)
		{
			  return FAIL;
		}
	
		else if (getLastMessage().contains("true"))
        	{
        		if (setLevel(level)==FAIL)
			{
				return FAIL;
			}
        	}
*/ 
      
		if(setKomi(komi)==FAIL)
		{
			return FAIL;
		}

		if(fixedHandicap(handicap)==FAIL)
		{
			return FAIL;
		}
	}
	else
	{
		quit();
		_response="Protocol version error";
		return FAIL;
	}

    busy = false;
	return OK;
}
Beispiel #30
0
int handleButtonClicked_loadFromSlotWindow(SDL_Event e){
	Button *lst = currentPage.btnList;
	int len = currentPage.btnListLen;
	Button curr;
	int quit = 0;
	int isSuccess = 1;

	for (int i = 0; i < len; i++){
		curr = lst[i];
		if (isClickInRect(e, curr.buttonsDestRect) == 1){
			if (curr.id >=1 && curr.id <=NUM_OF_SLOTS){
				// a slot was chosen - load from slot
				char path[100];
				if (userGuiSettings.savedSlot != 0){
					// need to deselect the prevButton
					Button prevChosenButton = getButtonAccordingToId(lst, len, userGuiSettings.savedSlot);
					sprintf(path, "%s%d%s", SLOT_BTN_URL, userGuiSettings.savedSlot, "_btn.bmp");
					isSuccess = deselectButton(path, prevChosenButton);
				}
				if (isSuccess == 1){
					userGuiSettings.savedSlot = curr.id;
					sprintf(path, "%s%d%s", SLOT_SELECTED_BTN_URL, userGuiSettings.savedSlot, "_btn.bmp");
					isSuccess = selectButton(path, curr);
				}
			}
			else{
				switch (curr.id)
				{
				case NUM_OF_SLOTS+1:
					isSuccess = navigatToPage("mainMenu");
					break;
				case NUM_OF_SLOTS+2:
					// load from chosen slot
					//check if there is no slot chosen
					if (userGuiSettings.savedSlot != 0){
						
						char path[100];
						char *slot = "./slots/slot";
						char *xmlStr = ".xml";
						sprintf(path, "%s%d%s", slot, userGuiSettings.savedSlot, xmlStr);
						clearBoard();
						fileData data = loadGame(path);
						isSuccess = saveLoadedData(data, 0);
						if (!isSuccess){
							// TBD - what do we need to do? Show a dialog?
						}

						// navigate to selection page
						isSuccess = navigatToPage("selectionWindow");
					}
					break;
				}
			}
			break;
		}
	}

	quit = !isSuccess;
	return quit;

}