Tic Tac Toe
unknown
c_cpp
5 months ago
2.2 kB
4
Indexable
#include <iostream> using namespace std; void printBoard(char board[3][3]) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << "[" << board[i][j] << "]"; } cout << endl; } } bool checkWinner(char player, char board[3][3]) { for (int i = 0; i < 3; 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 checkDraw(char board[3][3]) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == ' ') { return false; } } } return true; } void makeMove(char player, char board[3][3]) { int x, y; cout << "Enter the row and column: "; bool isInputOk = false; do { cin >> x >> y; if (board[x][y] != ' ') { cout << "Invalid move. Try again." << endl; continue; } board[x][y] = player; isInputOk = true; } while (!isInputOk); board[x][y] = player; } int main() { char board[3][3] = { {' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}, }; char player = 'X'; while (true) { printBoard(board); makeMove(player, board); if (checkWinner(player, board)) { cout << "Player " << player << " wins!" << endl; printBoard(board); break; } else if (checkDraw(board)) { cout << "Draw!" << endl; printBoard(board); break; } player = (player == 'X') ? 'O' : 'X'; } }
Editor is loading...
Leave a Comment