fork download
  1. #include <iostream>
  2. #include <stdexcept>
  3. #include <bits/stdc++.h>
  4.  
  5. using namespace std;
  6.  
  7. #define BOARDSIZE 3
  8.  
  9. /*
  10. | | | | | ==> presenceStat is 2*4 => one row for each player
  11. | | | | | ==> 1st col - row, 2nd-col, 3rd-principal diagnal, 4th - secondary diagnal
  12. */
  13.  
  14. class TicTacToe
  15. {
  16. private:
  17. int player;
  18. vector< vector < int > > presenceStat;
  19.  
  20. vector< vector < char > > board;
  21.  
  22. public:
  23. TicTacToe() : player(1), presenceStat(2, vector<int>(4, 0)),
  24. board(BOARDSIZE, vector<char>(BOARDSIZE, ' ')) {}
  25.  
  26. void printPresenceStat()
  27. {
  28. for (int i = 0; i < 2; i++)
  29. {
  30. for (int j = 0; j < 4; j++)
  31. {
  32. cout << presenceStat[i][j] << " ";
  33. }
  34. cout << endl;
  35. }
  36. }
  37.  
  38. void makeMove(int row, int col, int player)
  39. {
  40. cout << "makeMove " << row << " " << col << " " << player << endl;
  41. // try
  42. // {
  43. if (row < 0 || row >= BOARDSIZE || col < 0 || col >= BOARDSIZE || board[row][col] != ' ')
  44. {
  45. // throw runtime_exception("Invalid move");
  46. }
  47.  
  48. int rowIdx = player-1;
  49. bool isWin = false;
  50.  
  51. board[row][col] = rowIdx == 0 ? 'X' : 'O';
  52.  
  53. ((presenceStat[rowIdx][0] |= (1 << row)) != 7) ? : isWin = true ;
  54. ((presenceStat[rowIdx][1] |= (1 << col)) != 7) ? : isWin = true ;
  55. if (row == col)
  56. ((presenceStat[rowIdx][2] |= (1 << row)) != 7) ? : isWin = true ;
  57. if (row + col == BOARDSIZE-1)
  58. ((presenceStat[rowIdx][3] |= (1 << row)) != 7) ? : isWin = true ;
  59.  
  60. printPresenceStat();
  61.  
  62. //check for win
  63. if (isWin)
  64. cout << player << " won the match" << endl;
  65.  
  66. player = 3-player;
  67. /* }
  68. catch(exception& e)
  69. {
  70. cout e.what() << endl;
  71. } */
  72. }
  73.  
  74. };
  75.  
  76. int main() {
  77. TicTacToe* pGame = new TicTacToe();
  78. pGame->makeMove(0, 0, 1);
  79. pGame->makeMove(0, 1, 2);
  80. pGame->makeMove(1, 0, 1);
  81. pGame->makeMove(0, 2, 2);
  82. pGame->makeMove(2, 0, 1);
  83. return 0;
  84. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
makeMove 0 0 1
1 1 1 0 
0 0 0 0 
makeMove 0 1 2
1 1 1 0 
1 2 0 0 
makeMove 1 0 1
3 1 1 0 
1 2 0 0 
makeMove 0 2 2
3 1 1 0 
1 6 0 1 
makeMove 2 0 1
7 1 1 4 
1 6 0 1 
1 won the match