Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- char Array[3][3] = {{' ', ' ', ' '},{' ', ' ', ' '},{' ', ' ', ' '}};
- void drawTable() {
- printf(" --- --- --- \n| %c | %c | %c |\n --- --- --- \n| %c | %c | %c |\n --- --- --- \n| %c | %c | %c |\n --- --- ---\n",
- Array[0][0], Array[0][1], Array[0][2],
- Array[1][0], Array[1][1], Array[1][2],
- Array[2][0], Array[2][1], Array[2][2]);
- }
- void clearTable() {
- for (int a = 0; a < 3; a++) {
- for (int b = 0; b < 3; b++) {
- Array[a][b] = ' ';
- }
- }
- }
- int hasCombination(char 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, char p) {
- if (Array[a][b] == ' ') {
- Array[a][b] = p;
- return 1;
- }
- return 0;
- }
- void newTurn(char player) {
- int a, b;
- printf("%c's turn to enter a row (1, 2, or 3) and column (1, 2, or 3)\n>", player);
- std::cin >> a >> b;
- int successful = place(a - 1, b - 1, player);
- if (!successful) {
- printf("That space is already taken, try again.\n");
- newTurn(player);
- }
- }
- int hasWinner() {
- if (hasCombination('x')) {
- return 'x';
- } else if (hasCombination('o')) {
- return 'o';
- }
- return ' ';
- }
- void newCycle(char);
- void newGame(char player = 'x') {
- printf("\nStarting new game.\n");
- clearTable();
- newCycle(player);
- }
- void newCycle(char player) {
- drawTable();
- newTurn(player);
- int winner = hasWinner();
- if (winner != ' ') {
- printf("\n%c wins! Bravo!\n", player);
- drawTable();
- printf("New game? (y/n)\n");
- char option;
- std::cin >> option;
- if (tolower(option) == 'y') {
- newGame(player == 'x' ? 'o' : 'x');
- } else {
- printf("\nGoodbye!");
- }
- } else {
- newCycle(player == 'x' ? 'o' : 'x');
- }
- }
- int main() {
- newGame();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement