Tic-Tac-Toe
#include <iostream>
#include <time.h>
using namespace std;
const int ROWS = 3;
const int COLS = 3;
void printBoard(char board[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
cout << "-------------" << endl;
for (int j = 0; j < COLS; j++) {
cout << "| " << board[i][j] << " ";
}
cout << "|" << endl;
}
cout << "-------------" << endl;
}
bool winner(char board[ROWS][COLS]) {
if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] != '*') {
return true;
}
if (board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0] != '*') {
return true;
}
if (board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0] != '*') {
return true;
}
if (board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[0][0] != '*') {
return true;
}
if (board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] != '*') {
return true;
}
if (board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[0][2] != '*') {
return true;
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '*') {
return true;
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != '*') {
return true;
}
return false;
}
int main () {
char player;
int row, col, moves=0;
char board [ROWS][COLS] = {
{'', '', ''},
{'', '', ''},
{'', '', '*'}
};
cout << "Welcome to Tic Tac Toe!" << endl << endl;
printBoard(board);
do {
cout << endl << "Please enter row: ";
cin >> row;
cout << "Please enter col: ";
cin >> col;
cout << endl;
row -= 1;
col -=1;
moves ++;
if (moves % 2 == 0) {
player = 'O';
if (board[row][col] == '') {
board[row][col] = player;
} else {
cout << endl << "Space occupied, lose turn" << endl << endl;
moves--;
}
printBoard(board);
} else {
player = 'X';
if (board[row][col] == '') {
board[row][col] = player;
} else {
cout << endl << "Space occupied, lose turn" << endl << endl;
moves--;
}
printBoard(board);
}
if (winner(board) == true) {
cout << endl << "Player " << player << " wins" << endl;
return 0;
}
} while (moves < 9);
cout << endl << "Draw" << endl;
}