Created
August 18, 2014 12:57
-
-
Save ivycheung1208/61ca07303baed35ebb77 to your computer and use it in GitHub Desktop.
CC150 17.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* CC150 17.2 */ | |
// determine if someone has won a game of tic-tac-toe | |
// (expand to a full game!) | |
#include <iostream> | |
using namespace std; | |
// assume only one row satisfying the condition exists since the games ends once a player succeeded | |
// in placing three respective marks in a horizontal, vertical or diagonal row. | |
bool isEmpty(char grid) { return grid != 'x' && grid != 'o'; } | |
bool hasWon(char **board, int n) | |
{ | |
if (n < 1) | |
return false; | |
int i = 0, j = 0; | |
// check rows | |
for (i = 0; i != n; ++i) { | |
if (isEmpty(board[i][0])) | |
continue; | |
for (j = 0; j != n; ++j) { | |
if (board[i][j] != board[i][0]) | |
break; | |
} | |
if (j == n) { | |
cout << "Row #" << i << " won by " << board[i][0] << endl; | |
return true; | |
} | |
} | |
// check columns | |
for (i = 0; i != n; ++i) { | |
if (isEmpty(board[0][i])) | |
continue; | |
for (j = 0; j != n; ++j) { | |
if (board[j][i] != board[0][i]) | |
break; | |
} | |
if (j == n) { | |
cout << "Column #" << i << " won by " << board[0][i] << endl; | |
return true; | |
} | |
} | |
// check diagonal | |
for (i = 0; i != n; ++i) { | |
if (isEmpty(board[0][0]) || board[i][i] != board[0][0]) | |
break; | |
} | |
if (i == n) { | |
cout << "Diagonal won by " << board[0][0] << endl; | |
return true; | |
} | |
// check reverse diagonal | |
for (i = 0; i != n; ++i) { | |
if (isEmpty(board[0][n - 1]) || board[i][n - 1 - i] != board[0][n - 1]) | |
break; | |
} | |
if (i == n) { | |
cout << "Reverse diagonal won by " << board[0][n - 1] << endl; | |
return true; | |
} | |
cout << "No player won...keep going..." << endl; | |
return false; | |
} | |
int main() | |
{ | |
int n; | |
cout << "Board size: "; | |
cin >> n; | |
char **board = new char*[n]; | |
for (int i = 0; i != n; ++i) { | |
board[i] = new char[n]; | |
for (int j = 0; j != n; ++j) | |
cin >> board[i][j]; // represent with -/x/o | |
} | |
bool result = hasWon(board, n); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment