diff --git a/game.cpp b/game.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b79621e7403f34025eb9c9d273ece260950a32c2 --- /dev/null +++ b/game.cpp @@ -0,0 +1,72 @@ +#include "game.hpp" +#include <iostream> + +using namespace std; + +char board[SIZE][SIZE] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} }; + +void displayBoard() { + cout << "Tic-Tac-Toe Board:\n"; + for (int i = 0; i < SIZE; i++) { + for (int j = 0; j < SIZE; j++) { + cout << board[i][j] << " "; + } + cout << endl; + } +} + +bool checkWin(char player) { + for (int i = 0; i < SIZE; i++) { + if (board[i][0] == player && board[i][1] == player && board[i][2] == player) return true; + if (board[0][i] == player && board[1][i] == player && board[2][i] == player) return true; + } + if (board[0][0] == player && board[1][1] == player && board[2][2] == player) return true; + if (board[0][2] == player && board[1][1] == player && board[2][0] == player) return true; + return false; +} + +bool isDraw() { + for (int i = 0; i < SIZE; i++) + for (int j = 0; j < SIZE; j++) + if (board[i][j] != 'X' && board[i][j] != 'O') return false; + return true; +} + +void playerMove(char player) { + int choice; + cout << "Player " << player << ", enter your move (1-9): "; + cin >> choice; + + int row = (choice - 1) / SIZE; + int col = (choice - 1) % SIZE; + + if (choice >= 1 && choice <= 9 && board[row][col] != 'X' && board[row][col] != 'O') { + board[row][col] = player; + } else { + cout << "Invalid move. Try again.\n"; + playerMove(player); + } +} + +void gameLoop() { + char player = 'X'; + while (true) { + displayBoard(); + playerMove(player); + + if (checkWin(player)) { + displayBoard(); + cout << "Player " << player << " wins!\n"; + break; + } + + if (isDraw()) { + displayBoard(); + cout << "It's a draw!\n"; + break; + } + + player = (player == 'X') ? 'O' : 'X'; + } +} + diff --git a/game.hpp b/game.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b29387bfe6fc325a8a63aa9acfbd5a342deccac5 --- /dev/null +++ b/game.hpp @@ -0,0 +1,14 @@ +#ifndef GAME_HPP +#define GAME_HPP + +const int SIZE = 3; +extern char board[SIZE][SIZE]; + +void displayBoard(); +bool checkWin(char player); +bool isDraw(); +void playerMove(char player); +void gameLoop(); + +#endif // GAME_HPP + diff --git a/main b/main new file mode 100644 index 0000000000000000000000000000000000000000..a97e477f683de7ed59d0f0c8579657c4baace675 --- /dev/null +++ b/main @@ -0,0 +1,7 @@ +#include "game.hpp" + +int main() { + gameLoop(); + return 0;; +} +