void TicTacToeGame::updateBoard(int iPlayer, int iChoice) { int i = (iChoice / BOARD_SIZE) + ((iChoice % BOARD_SIZE) != 0 ? 1 : 0); int j = (iChoice % BOARD_SIZE) == 0 ? BOARD_SIZE : (iChoice % BOARD_SIZE); //iChoice is 1 indexed based and i,j are 0 indexed based. So we need to do -1 from both --i; --j; if (getBoardElement(i, j) != EMPTY) { throw std::string("Trying to update already assigned field"); } if (iPlayer == Player1) { setBoardValue(getPlayer1()->getSign(), i, j); } else { setBoardValue(getPlayer2()->getSign(), i, j); } }
void TicTacToeGame::initializeBoard() { if (!getBoard()) { m_board = new BoardValueType*[BOARD_SIZE]; for (int i=0; i<BOARD_SIZE; ++i) { m_board[i] = new BoardValueType[BOARD_SIZE]; } } for (int i=0; i<BOARD_SIZE; ++i) { for (int j=0; j<BOARD_SIZE; ++j) { setBoardValue(EMPTY, i, j); } } }
/* * Internal method that recursively solves the puzzle. * * Parameters: * x_cord: The x-coordinate on the board. Should be between 0 * and 8, inclusive * y_cord: The y-coordinate on the board. Should be between 0 * and 8, inclusive. * * Return: * True if solved, false if unsolvable. If solved, the puzzle's * current state is solved. You can print the puzzle to see * the solution. */ bool SudokuPuzzle::solve(int x_cord, int y_cord) { // Only solve piece if not already solved (given) if (board[x_cord][y_cord] != 0) { // If value works, on to next if (verifyValue(x_cord,y_cord)) { // If last piece, puzzle solved! if (x_cord == 8 && y_cord == 8) { return true; } // Find next slot on this row int next_x = x_cord+1; int next_y = y_cord; // If at end of row, start next if (next_x >= 9) { next_x = 0; next_y++; } // Move on to next piece return solve(next_x, next_y); } // Value doesn't work. Early guess is bad else { return false; } } // If value already defined // There isn't a value already for position. // Guess all the values until one works for (int val=1; val<10; val++) { setBoardValue(x_cord, y_cord, val); // If value works, on to next if (verifyValue(x_cord,y_cord)) { // If last piece, puzzle solved! if (x_cord == 8 && y_cord == 8) { return true; } // Find next slot on this row int next_x = x_cord+1; int next_y = y_cord; // If at end of row, start next if (next_x >= 9) { next_x = 0; next_y++; } // Move on to next piece //return solve(next_x, next_y); if (solve(next_x, next_y)) { return true; } } } // Remove value. Going to backtrack. If value remained, // then would think its part of solution. board[x_cord][y_cord] = 0; // If gets here, must backtrack. No solution // for path. return false; } // SudokuPuzzle::solve(int, int)