diff --git a/main.cpp b/main.cpp index 0506f2e..4789232 100644 --- a/main.cpp +++ b/main.cpp @@ -5,8 +5,6 @@ #include #include -#define BOARDSIZE 9 - using namespace std; class Board; @@ -22,9 +20,11 @@ class Board { private: vector board; Player *player1, *player2; + int currentPlayer; public: void initBoard() { - for (int i=0; igetMove(*this)); + else makeMove(player2->getMove(*this)); + currentPlayer = currentPlayer % 2 + 1; + } + bool makeMove(int move) { if (!isValidMove(move)) return false; + board[move] = currentPlayer; } bool isValidMove(int move) { return move >= 0 && move < 9 && board[move] == 0; } + // returns 0 if no one has won + // 1 for player 1 + // 2 for player 2 + int hasWon() { + int a[2] = { 1, 2 }; + for (int p : a) { + int conditions[8][3] = + { {0,1,2}, + {3,4,5}, + {6,7,8}, + {0,3,6}, + {1,4,7}, + {2,5,8}, + {2,4,6}, + {0,4,8} }; + for (auto &condition : conditions) { + bool won = true; + for(auto &part : condition) { + won = won && board[part] == p; + } + if (won) return p; + } + } + return 0; + } + void print() { + printf("\n"); for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { - printf(" %d |", board[i*3+j]); + int state = board[i*3+j]; + printf(" %c |", state == 0 ? ' ' : state == 1 ? 'X' : 'O'); } printf("\e[1D\e[0K\n---+---+---\n"); } - printf("\e[1A\e[0K"); + printf("\e[1A\e[0K\n"); } }; @@ -72,7 +108,7 @@ class User : public Player { int move; cout << "Tile: "; cin >> move; - if (b.isValidMove(move)) return move; + if (b.isValidMove(move-1)) return move-1; cout << endl << "Invalid move\e[2A"; } } @@ -107,7 +143,17 @@ int main() { } Board main(player1, player2); - main.print(); + int winningPlayer = 0; + while (true) { + main.print(); + + winningPlayer = main.hasWon(); + if (winningPlayer != 0) break; + + main.nextMove(); + } + + printf("Player %d won!", winningPlayer); delete player1; delete player2;