Difference: CodeArray2 (2 vs. 3)

Revision 32017-10-10 - JimSkon

Line: 1 to 1
 
META TOPICPARENT name="WebHome"
Added:
>
>
<-- SyntaxHighlightingPlugin -->
#include<iostream>
using namespace std;
void displayBoard(char board[3][3]);
void getMove(char b[3][3], char player, int &r, int &c);
char checkWin(char board[3][3]);
int main() {
    char board[3][3] = {' ',' ',' ',' ',' ',' ',' ',' ',' '};
    bool gameOver = false;
    int row, col;
    char curPlayer = 'X';
    int moves = 0;
    do {
        getMove(board,curPlayer, row, col);
        board[row - 1][col - 1] = curPlayer;
        if (curPlayer == 'X') {
            curPlayer = 'O';
        } else {
            curPlayer = 'X';
        }
        displayBoard(board);
        char winner = checkWin(board);
        moves++;
        if (winner!= ' ') {
            cout << winner << " Wins!!!" << endl;
            gameOver=true;
        } else if (moves>=9) {
            gameOver = true;
            cout << "No Winner!" << endl;
        }
    } while (!gameOver);
    return 0;
}

void displayBoard(char board[3][3]) {
    for (int r = 0; r < 3; r++) {
        for (int c = 0; c < 3; c++) {
            cout << board[r][c] << " ";
        }
        cout << endl;
    }
}
bool inRange(int x) {
    return (x>0 && x<4);
}
void getMove(char b[3][3], char player, int &r, int &c) {
    bool moveBad = true;
    do {
        cout << player << " enter row and column (1-3):";
        cin >> r >> c;
        if (!inRange(r)||!inRange(c)||b[r-1][c-1]!=' ') {
            cout << "Row and Column must be 1-3, and unused!" << endl;
        } else {
            moveBad = false;
        }
    } while (moveBad);
}
char checkWin(char b[3][3]){
    for (int r=0;r<3;r++) {
        if (b[r][0]!= ' '&&
                (b[r][0]==b[r][1])&&(b[r][1]==b[r][2])) {
            return b[r][0];
        }
    }
    for (int c=0;c<3;c++) {
        if (b[0][c]!= ' '&&
                (b[0][c]==b[1][c])&&(b[1][c]==b[2][c])) {
            return b[0][c];
        }
    }
    return ' ';
}
 
<-- end SyntaxHighlightingPlugin -->
 

Functions Sample code 2

 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2019 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback