Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- int Array[3][3] = {{0,0,0},{0,0,0},{0,0,0}};
- string findSymbolFromNum(int x) {
- switch (x) {
- case 1: return "X"; break;
- case 2: return "O"; break;
- default: return "~";
- }
- }
- void drawTable() {
- cout << "\n-----------\n";
- for (int a=0; a<3; a++) {
- cout << "|";
- for (int b=0; b<3; b++) {
- cout << " " << findSymbolFromNum(Array[a][b]) << " ";
- }
- cout << "|\n";
- }
- cout << "-----------\n\n";
- }
- void clearTable() {
- for (int a=0; a<3; a++) {
- for (int b=0; b<3; b++) {
- Array[a][b] = 0;
- }
- }
- }
- int hasCombination(int x) {
- return
- ((Array[0][0] == x && Array[0][1] == x && Array[0][2] == x) || // xxx ??? ???
- (Array[1][0] == x && Array[1][1] == x && Array[1][2] == x) || // ??? xxx ???
- (Array[2][0] == x && Array[2][1] == x && Array[2][2] == x) || // ??? ??? xxx
- (Array[0][0] == x && Array[1][0] == x && Array[2][0] == x) || // x?? x?? x??
- (Array[0][1] == x && Array[1][1] == x && Array[2][1] == x) || // ?x? ?x? ?x?
- (Array[0][2] == x && Array[1][2] == x && Array[2][2] == x) || // ??x ??x ??x
- (Array[0][0] == x && Array[1][1] == x && Array[2][2] == x) || // x?? ?x? ??x
- (Array[2][2] == x && Array[1][1] == x && Array[0][0] == x)); // ??x ?x? x??
- }
- int place(int a, int b, int x) {
- if (Array[a][b] == 0) {
- Array[a][b] = x;
- return 1;
- } else {
- return 0;
- }
- }
- void newTurn(int x) {
- int a;
- int b;
- string player = findSymbolFromNum(x);
- cout << player << "'s turn to enter a row (1, 2, or 3)\n> ";
- cin >> a;
- cout << player << "'s turn to enter a column (1, 2 or 3)\n> ";
- cin >> b;
- int successful = place(a-1, b-1, x);
- if (!successful) {
- cout << "That space is already taken, try again.\n";
- newTurn(x);
- }
- }
- int hasWinner() {
- if (hasCombination(1)) {
- return 1;
- } else if (hasCombination(2)) {
- return 2;
- } else {
- return 0;
- }
- }
- void newCycle(int x);
- void newGame(int x=1) {
- int z;
- cout << "Type in a number and press enter for new game.\n";
- cin >> z;
- cout << "\nStarting new game.\n";
- clearTable();
- newCycle(x);
- }
- void newCycle(int x) {
- drawTable();
- string player = findSymbolFromNum(x);
- newTurn(x);
- int winner = hasWinner();
- if (winner != 0) {
- cout << "\n" << player << " wins! Bravo!\n";
- drawTable();
- newGame(x == 1 ? 2 : 1);
- } else {
- newCycle(x == 1 ? 2 : 1);
- }
- }
- int main() {
- newGame();
- }
Advertisement
Add Comment
Please, Sign In to add comment