/* * Extension: Checks and adds to hash table using Zobrist hash function */ void generateUniqueBoardHash(BoardNode currentBoard, int rowMove, int colMove, int currRow, int currCol) { int hashKey; BoardNode generatedBoard; generatedBoard = makeMove(copyParentToChild(currentBoard,createBoard(currentBoard)),rowMove,colMove,currRow,currCol,DELETE); hashKey = generateHashKey(generatedBoard); if(hashBoard(hashKey,generatedBoard)) { addToQueue(generatedBoard); checkTarget(generatedBoard); } }
Board* generateBoardsFromConfigurationVectors(BoardPieces** piecesVector, int cont) { Board* boardVector; int i; boardVector=(Board*)malloc(sizeof(Board)*cont); for(i=0;i<cont;i++) { boardVector[i]=createBoard(boardVector[i], piecesVector[i]); } return boardVector; }
// Constructor and destrcutor LeaderBoard::LeaderBoard(QWidget *parent) : QDialog(parent), ui(new Ui::LeaderBoard){ ui->setupUi(this); lBoardMd = new LeaderBoardModel(); lBoardMd->leader(scores); // Debugging values //clearleadrboard(); /*ScoreEntry p("Matthew", 100); ScoreEntry p2("Caleb", 100); ScoreEntry p3("Ian", 100); ScoreEntry p4("Matt", 100); ScoreEntry p5("Jean", 100); ScoreEntry p6("Dan", 10); ScoreEntry p7("Sand", 1010); lBoardMd->addEntry(p); lBoardMd->addEntry(p2); lBoardMd->addEntry(p3); lBoardMd->addEntry(p2); lBoardMd->addEntry(p4); lBoardMd->addEntry(p6); lBoardMd->addEntry(p7);*/ // Checks to see if file exist in order to create temporary one /* ifstream file; file.open("leaderboard.txt"); if (file.is_open()) { std::string temp; int score; std::string name; for(int g=0;g<10;g++) { file >>temp; file >> score; file >> name; std::string res; // Stream conversation ostringstream convert; // Instert convert << score; // Convert to string res = convert.str(); scores.push_back(res); scores.push_back(name); } file.close(); } else cout << "Unable to open file" << endl; */ createBoard(); }
void BoggleBoard::initRandomBoard() { //Random boards are 4x4 destroyBoard(); createBoard(4, 4); for(unsigned int r=0;r<ROWS;r++) { for(unsigned int c=0;c<COLS;c++) { int index = this->returnIndex(r, c) % this->diceBag.size(); std::string face = this->diceBag[index]->getRandomFace(); this->board[r][c] = face; } } }
Game::Game() { createBoard(); systable[empty] = '.'; systable[green] = 'g'; systable[blue] = 'b'; systable[cyan] = 'c'; systable[red] = 'r'; systable[magenta] = 'm'; systable[orange] = 'o'; systable[yellow] = 'y'; };
/* *Basic: adds unqiue boards to linear linked list queue */ void generateUniqueBoardWithMove(BoardNode currentBoard, int rowMove, int colMove, int currRow, int currCol) { //!Create a blank board, copy parent board to it, make the move, check if it //!is unique, add it to queue BoardNode generatedBoard; if((generatedBoard = compBoardWithList(makeMove(copyParentToChild(currentBoard,createBoard(currentBoard)),rowMove,colMove,currRow,currCol,DELETE))) != NULL) { addToQueue(generatedBoard); checkTarget(generatedBoard); } else { freeBoard(generatedBoard); } }
MainWindow::MainWindow(QWidget* parent):QMainWindow(parent){ this->move(300,200); this->setWindowIcon(QIcon(":/images/img/logo.png")); gl=0; createNormalGameLogic(); initializeWidgets(); createBoard(Board::MAX_ROW_NUM,Board::MAX_COLUMN_NUM); createActions(); createMenuBar(); createStatusBar(); this->newGame(10,10,10); //start a new game by default }
void GUIBoggleBoard::initRandomBoard() { //Random boards are 4x4 destroyBoard(); createBoard(4, 4); for(unsigned int r=0;r<ROWS;r++) { for(unsigned int c=0;c<COLS;c++) { // using modular of index to get one diceBag from 16 diceBag int index = this->returnIndex(r, c) % this->diceBag.size(); // choose randomly from one of six faces std::string face = this->diceBag[index]->getRandomFace(); this->board[r][c] = face; } } }
TEST(Board_test, CreateBoard) { EXPECT_EQ(0, createBoard()); EXPECT_EQ(EMPTY,getBoardCell(0,0)); EXPECT_EQ(EMPTY,getBoardCell(0,1)); EXPECT_EQ(EMPTY,getBoardCell(0,2)); EXPECT_EQ(EMPTY,getBoardCell(1,0)); EXPECT_EQ(EMPTY,getBoardCell(1,1)); EXPECT_EQ(EMPTY,getBoardCell(1,2)); EXPECT_EQ(EMPTY,getBoardCell(2,0)); EXPECT_EQ(EMPTY,getBoardCell(2,1)); EXPECT_EQ(EMPTY,getBoardCell(2,2)); }
int main(){ board *board = createBoard(); pawnTest(board); bishopTest(board); kingTest(board); /*clean up all the mallocs*/ deleteAllCells(board); /*deletes all pieces as well*/ printf("All cells and pieces freed\n"); deleteBoard(board); printf("Board freed\n"); exit(0); return 0; }
int main(void) { char **board = createBoard(); /* Begin main game */ coord currentPos; char currentPlayer = crossChar; int i; for(i=0; gameOver(board) == FALSE; i++) { if(i == 0) { printBoard(board, stdout); printf("It's %c's turn.\nChoose co-ordinates: ", currentPlayer); } else { puts("Incorrect input, please try again"); } currentPos = getInput(stdin); if(currentPos.row == -1) continue; if( placeTurn(board, currentPos, currentPlayer) == FALSE ) continue; if(currentPlayer == crossChar) currentPlayer = naughtChar; else currentPlayer = crossChar; i = -1; } if(currentPlayer == crossChar) currentPlayer = naughtChar; else currentPlayer = crossChar; if(gameOver(board) == win) printf("Game over. %c wins.\n", currentPlayer); else puts("Game over. Draw.\n"); printBoard(board, stdout); freeBoard(board); return EXIT_SUCCESS; }
/* validMove should return true IFF the chosen column is not full */ void test_validMove() { board_type *board = createBoard(X, Y); int i; CU_ASSERT_TRUE(validMove(board, 0)); for(i = 0; i < Y - 1; i++) makeMove(board, 0); CU_ASSERT_TRUE(validMove(board, 0)); makeMove(board, 0); CU_ASSERT_FALSE(validMove(board, 0)); free(board); }
int main() { //setting values int numProcessors=3,boardSize=50,tileSize=10,maxDensity=50,maxSteps=10,seed=0,interactive=0; //error checking if(boardSize%tileSize!=0) { printf("Invalid args, b mod t must equal 0\n"); return 0; } else if(numProcessors<1) { printf("Invalid args, p must be > 0\n"); return 0; } else if(boardSize<2) { printf("Invalid args, b must be > 1\n"); return 0; } //Setting up board Board * b = createBoard(boardSize); randBoard(b, &seed); int tileGridSize=sqrt((boardSize*boardSize)/(tileSize*tileSize)); Tile* (tiles[tileGridSize][tileGridSize]); for(int i=0; i<tileGridSize; i++) { for(int j=0; j<tileGridSize; j++) { tiles[i][j] = (Tile*) calloc(sizeof(Tile), 1); tiles[i][j]->x=i*tileSize; tiles[i][j]->y=j*tileSize; } } //work loop do { printBoard(b); fgetc(stdin); } while(stepRB(b)!=0); //cleanup for(int i=0; i<tileGridSize; i++) { for(int j=0; j<tileGridSize; j++) { free(tiles[i][j]); } } destroyBoard(b); return 0; }
/** * A function to execute all the posible movements for a piece, and creating all the new posible boards */ void Board::execute() { matrix = getMatrix(); if (finalReached()) { return; } bool incheck = isInCheck(); std::vector<Piece *> pieces; if (turn == WHITE) { pieces = whitePieces; } else { pieces = blackPieces; } for (std::vector<Piece *>::iterator pieceIt = pieces.begin(); pieceIt != pieces.end(); ++pieceIt) { std::vector<Move *> *moves = (*pieceIt)->makeMove(matrix); removeInvalidMoves(*pieceIt, moves); std::vector<Board *> child_boards; #pragma omp task untied { for (std::vector<Move *>::iterator moveIt = moves->begin(); moveIt != moves->end(); ++moveIt) { Board *board = createBoard(*pieceIt, *moveIt, incheck, turnsLeft - 1); if (board != nullptr) { board->execute(); board->updateFather(); child_boards.push_back(board); } delete (*moveIt); } for (std::vector<Board *>::iterator child = child_boards.begin(); child != child_boards.end(); ++child) { if ((*child) != bestBoard) delete (*child); } } delete moves; } #pragma omp taskwait }
int main(void) { int fini,x,y; fini=0; initPlayer(); createBoard(); while(!fini) { displayBoard(); if(getPlayer()==CROSS) { printf("Cross to play\n"); } else { printf("Circle to play\n"); } printf("column?: "); scanf("%d",&x); printf("line?: "); scanf("%d",&y); if(putPiece(x,y,getPlayer())==0) { fini=checkGameStatus(); if(!fini) { changePlayer(); } }else { printf("you can't play here!\n"); } } displayBoard(); if(getPlayer()==CROSS) { printf("Cross won \\o/\n"); } else { printf("Circle won \\o/\n"); } }
int main(void) { int size; printf("Enter board dimensions (n), n>=6 and n<=21: "); scanf("%d", &size); char board[21][21]; createBoard(size, board); char compPlayer[10]; bool humanUserWhite; printf("Computer playing B or W?: "); scanf("%s", &compPlayer); if (compPlayer[0] == 'B') humanUserWhite = true; else humanUserWhite = false; setBlocked(size, board); playGame(size, board, humanUserWhite); return (EXIT_SUCCESS); }
// Function sets the size of the board (i.e., the nuber of rows and // columns). The rows and columns values (if they are to be changed from // the defaults) must be set before the N value. The rows and columns // values are checked to ensure they are within the allowed range. This // function calls the private createBoard() function to create the board. // Parameters: int r: value to set as number of rows // int c: value to set as number of columns // Returns: true if rows and columns values were set, // false if an error occured (out of range, // etc.) // Postcondition: rows and columns values set to passed values // if they were valid bool Board::setSize(int r, int c) { // check rows range if (r >= MIN_ROWS && r <= MAX_ROWS) { // check columns range if (c >= MIN_COLUMNS && c <= MAX_COLUMNS) { rows = r; columns = c; createBoard(); return true; } else { std::cout << "setSize: Error, column value out of range." << std::endl; return false; } } else { std::cout << "setSize: Error, row value out of range." << std::endl; return false; } }
GUIBoggleBoard::GUIBoggleBoard(const char* lexfilename, unsigned int rows, unsigned int cols) { // Initialize the board createBoard(rows, cols); initDiceBag(); if(lexfilename) { //added to DEBUG // Initialize the lexicon this->lexicon_filename = lexfilename; std::ifstream infile; infile.open(this->lexicon_filename.c_str()); if(! infile.is_open()) { std::cout<<"Could not open lexicon file " << lexfilename << ", exiting." <<std::endl; exit(-1); } std::cout<<"Reading lexicon from " << lexfilename << "..." <<std::endl; std::string word; int i=0; this->lexicon_words.clear(); while(infile.is_open() && infile.good()) { std::getline(infile,word); if(word.size() < 1) continue; // lowercase the word // std::cerr << word << std::endl; std::transform(word.begin(), word.end(), word.begin(), ::tolower); // std::cerr << " to " << word << std::endl; this->lexicon_words.insert(word); i++; } std::cout << this->lexicon_words.size() << " distinct words read from " << lexfilename << "." <<std::endl; infile.close(); } //added to DEBUG srand(time(NULL)); }
/* Make sure that makeMove, validMovesLeft and undoMove work correctly in a * 'normal' situation. */ void test_moves_properly() { board_type *board = createBoard(X, Y); int i, j; for(i = 0; i < X; i++) { for(j = 0; j < Y; j++) { makeMove(board, i); } } CU_ASSERT_FALSE(validMovesLeft(board)); CU_ASSERT_EQUAL(board->lm, (X * Y) + LM_INIT); for(i = 0; i < X; i++) { for(j = 0; j < Y; j++) { undoMove(board); } } CU_ASSERT_EQUAL(board->lm, LM_INIT); CU_ASSERT_TRUE(validMovesLeft(board)); free(board); }
void Game::clearBoard() { board.clear(); createBoard(); }
void test_setup(){ g_board = createBoard(NCOLS, NROWS); }
int main(int argc, char **argv){ #ifdef DEBUG DEBUG_FILE = fopen("debug.txt", "w"); #endif initscr(); keypad(stdscr, TRUE); noecho(); clear(); start_color(); init_pair(COL_BLUE, COLOR_BLUE, COLOR_BLACK); init_pair(COL_YELLOW, COLOR_YELLOW, COLOR_BLACK); init_pair(COL_RED, COLOR_RED, COLOR_BLACK); init_pair(COL_WHITE, COLOR_WHITE, COLOR_BLACK); init_pair(COL_GREEN, COLOR_GREEN, COLOR_BLACK); init_pair(COL_CYAN, COLOR_CYAN, COLOR_BLACK); WINDOWMAX_Y = getmaxy(stdscr); WINDOWMAX_X = getmaxx(stdscr); INPUTMODE = INM_NORMAL; dprintf("Window size is %ix%i\n", WINDOWMAX_X, WINDOWMAX_Y); USECOLOR = 1; GCRUNFREQ = 50; CONSIZE = WINDOWMAX_Y - CHUNKSIZE - 5; const char *PATTERN = NULL; const char *BOARDNAME = NULL; int getoptval; while((getoptval = getopt(argc, argv, "cg:p:n:s:")) != -1){ switch(getoptval) { //Disable color case 'c': USECOLOR = 0; break; case 'p': PATTERN = optarg; break; case 'n': BOARDNAME = optarg; break; case 'g': GCRUNFREQ = atoi(optarg); break; case 's': CONSIZE = atoi(optarg); break; } } CONSIZE = clamp(CONSIZE, 5, 15); consoleBuffer = calloc(CONSIZE * GSTRINGSIZE, 1); cprintf("Welcome to the game of life! Press space/zxc to begin!"); cprintf("Use arrows/wasd to move. Press q to quit."); struct board *b; if(PATTERN){ b = readNewBoard(PATTERN); if(BOARDNAME){ setBoardName(b, BOARDNAME); } }else{ b = createBoard(BOARDNAME); initializeBoard(b); } //START TESTS /*#define on(x, y) curChunk(b)->board[at(x, y)] = 1*/ /*on(1, 1);*/ /*on(2, 2);*/ /*on(3, 2);*/ /*on(2, 3);*/ /*on(3, 1);*/ /*goto CLEANUP;*/ //END TESTS while(1){ erase(); drawBoard(b); inputRenderer(); consoleRenderer(); refresh(); if(!input(b)) goto CLEANUP; } CLEANUP: #ifdef DEBUG fclose(DEBUG_FILE); #endif free(consoleBuffer); freeBoard(b); endwin(); printf("Program complete"); return 0; }
int main(int argc, char** argv) { // Initialize everything double begTree, endTree, endMiniMax; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &threads); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int i; graph = createBoard(); maxPlayer = (struct Player*) malloc(sizeof(struct Player)); maxPlayer->num_walls = 10; maxPlayer->position = (int)sqrt(NUM_NODES)/2 + 1; maxPlayer->label = MAX_PLAYER; minPlayer = (struct Player*) malloc(sizeof(struct Player)); minPlayer->num_walls = 10; minPlayer->position = (NUM_NODES) - (int)sqrt(NUM_NODES)/2; minPlayer->label = MIN_PLAYER; graph->player = maxPlayer; graph->opponent = minPlayer; struct BFTreeNode *head_nodes[threads+3]; begTree = timer(); // Create the game tree createGameTreeParallel(graph,DEPTH,threads, head_nodes); endTree = timer(); int proc_result, total_result; MPI_Status status; // Handle the special case of multiple subtrees if (rank == threads-1) { int x = 0; for (x = 0; x < 3; x++) { if (head_nodes[rank+x] != NULL ){ if (head_nodes[rank+x]->nodeWrapped->level % 2 == 0) { head_nodes[rank+x]->nodeWrapped->evaluation = minimax(head_nodes[rank+x],DEPTH-head_nodes[rank+x]->nodeWrapped->level,MAX_PLAYER); } else { head_nodes[rank+x]->nodeWrapped->evaluation = minimax(head_nodes[rank+x],DEPTH-head_nodes[rank+x]->nodeWrapped->level,MIN_PLAYER); } } } // Receive the minimax results to include in the master tree for (i = 0; i < threads-1; i++) { MPI_Recv(&head_nodes[i]->nodeWrapped->evaluation,1,MPI_INT,i,0,MPI_COMM_WORLD,&status); } // Calculate the master tree total_result = minimax(game_tree_root,DEPTH-head_nodes[rank]->nodeWrapped->level,MAX_PLAYER); printf(" Final Evaluation is : %d \n",total_result); } else { // Produce results for any processors that only have one subtree if (head_nodes[rank]->nodeWrapped->level % 2 == 0) { proc_result = minimax(head_nodes[rank],DEPTH-head_nodes[rank]->nodeWrapped->level,MAX_PLAYER); } else { proc_result = minimax(head_nodes[rank],DEPTH-head_nodes[rank]->nodeWrapped->level,MIN_PLAYER); } // Send results to the final process MPI_Send(&proc_result,1,MPI_INT,threads-1,0,MPI_COMM_WORLD); } endMiniMax = timer(); // Display final timing information printf("\nBuilding Tree -- Execution time : %.10e\n", endTree - begTree); printf("\nMiniMax -- Execution time : %.10e\n", endMiniMax - endTree); printf("\nTotal -- Execution time : %.10e\n", endMiniMax - begTree); //releaseTree(head_nodes[rank]); //releaseTree(game_tree_root); //printGraph(graph); free(maxPlayer); free(minPlayer); free(graph); MPI_Finalize(); }
static void createdGameHasGivenBoard(void) { Board board = createBoard(13,19); setBoardCell(&board, createBoardCoord(4,5), blackBoardCell); Game game = createGame(board); assert(getBoardCell(&game.board, createBoardCoord(4,5)) == blackBoardCell); }
static Game exampleNotStartedGame(void) { Board *board = malloc(sizeof(board)); *board = createBoard(13,19); return createTestGame(*board); }
/* winnerIs should accept scores of four in horizontal, vertical and both * diagonal directions. Should return the correct winning player and IFF there * are four points in a row. */ void test_winnerIs() { board_type *board = createBoard(X, Y); int i, j; CU_ASSERT_EQUAL(winnerIs(board), 0); for(i = 0; i < 4; i++) { board->current_player = PLAYER_ONE; makeMove(board, i); } CU_ASSERT_EQUAL(winnerIs(board), PLAYER_ONE); for(i = 0; i < 4; i++) undoMove(board); for(i = 0; i < 4; i++) { board->current_player = PLAYER_TWO; makeMove(board, i); } CU_ASSERT_EQUAL(winnerIs(board), PLAYER_TWO); for(i = 0; i < 4; i++) undoMove(board); /* Bottom left to top right diagonal */ for(i = 2; i < 5; i++) { for(j = i; j < 5; j++) { board->current_player = PLAYER_TWO; makeMove(board, i); } } for(i = 2; i < 6; i++) { board->current_player = PLAYER_ONE; makeMove(board, i); } CU_ASSERT_EQUAL(winnerIs(board), PLAYER_ONE); /* Bottom left to top right diagonal */ for(i = 2; i < 6; i++) { for(j = i; j < 6; j++) undoMove(board); } /* Bottom left to top right diagonal */ for(i = 2; i < 5; i++) { for(j = 5; j > i; j--) { board->current_player = PLAYER_ONE; makeMove(board, i); } } for(i = 2; i < 6; i++) { board->current_player = PLAYER_TWO; makeMove(board, i); } CU_ASSERT_EQUAL(winnerIs(board), PLAYER_TWO); undoMove(board); CU_ASSERT_EQUAL(winnerIs(board), 0); free(board); }
bool MyFrameListener::frameStarted(const Ogre::FrameEvent& evt) { Ogre::Vector3 vt(0,0,0); Ogre::Real deltaT = evt.timeSinceLastFrame; Ogre::Real tSpeed = 20.0; int fps = 1.0 / deltaT; _keyboard->capture(); if(_keyboard->isKeyDown(OIS::KC_ESCAPE)) return false; if(_keyboard->isKeyDown(OIS::KC_0)) // reset { if (_gameState == 1) { _gameState = 0; deleteBoard(); _overlayManager->getByName("Title")->show(); } } if(_keyboard->isKeyDown(OIS::KC_1)) // jugar { if (_gameState == 0) { _gameState = 1; createBoard(); _overlayManager->getByName("Title")->hide(); _overlayManager->getByName("Win")->hide(); _overlayManager->getByName("Lose")->hide(); } } //if(_keyboard->isKeyDown(OIS::KC_2)) return false; // Captura del raton _mouse->capture(); int posx = _mouse->getMouseState().X.abs; int posy = _mouse->getMouseState().Y.abs; // Dibujado del cursor Ogre::OverlayElement *oe; oe = _overlayManager->getOverlayElement("cursor"); oe->setLeft(posx); oe->setTop(posy); // Accion del raton bool mbleft = _mouse->getMouseState().buttonDown(OIS::MB_Left); if (mbleft) { Ogre::Ray r = setRayQuery(posx, posy, 1); Ogre::RaySceneQueryResult &result = _raySceneQuery->execute(); Ogre::RaySceneQueryResult::iterator it; it = result.begin(); //AGUA if (it != result.end()) { if (it->movable->getParentSceneNode()->getName() != "nodeG") { Ogre::Vector3 pos = it->movable->getParentSceneNode()->getPosition(); it->movable->detachFromParent(); // tirada del CPU. int lResult = 0; do { lResult = playCPU(); if (endGame()!=0) { _gameState = 0; deleteBoard(); _overlayManager->getByName("Title")->show(); _overlayManager->getByName("Lose")->show(); } } while ((lResult == 1) && (_gameState==1)); } } //TOCADO r = setRayQuery(posx, posy, 2); Ogre::RaySceneQueryResult &resultShip = _raySceneQuery->execute(); it = resultShip.begin(); if (it != resultShip.end()) { if (it->movable->getParentSceneNode()->getName() != "nodeG") { Ogre::Vector3 pos = it->movable->getParentSceneNode()->getPosition(); it->movable->detachFromParent(); // Creacion de otro cubo para cuando haya barco. Ogre::Entity* ent1; ent1 = _sceneManager->createEntity("CuboBarco.mesh"); ent1->setQueryFlags(4); Ogre::SceneNode* node1 = _sceneManager->createSceneNode(); node1->attachObject(ent1); node1->translate(pos.x,pos.y,pos.z); _sceneManager->getRootSceneNode()->addChild(node1); _maxFires--; // no tira CPU if (endGame()!=0) { _gameState = 0; deleteBoard(); _overlayManager->getByName("Title")->show(); _overlayManager->getByName("Win")->show(); } } } } return true; }