Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- void printBoard(char[][3]);
- void getMove(int, int(&)[2]);
- void doMove(int&, char(&)[3][3], int[2]);
- void checkBoard(int, char[][3], int&);
- int main() {
- int moveXY[2] = {0, 0}; // Variable used for selecting moves
- char tic[3][3]; // Board
- int turn = 0; // Current turn
- int win = 0; // Has someone won; 0 = ...nah
- for (int i = 0; i < 3; i++) // Initialize board
- for (int j = 0; j < 3; j++)
- tic[i][j] = '*';
- printBoard(tic);
- while (win == 0) { // The game
- getMove(turn, moveXY);
- doMove(turn, tic, moveXY);
- printBoard(tic);
- checkBoard(turn, tic, win);
- if (win < 0)
- cout << "Player 1 wins!" << endl;
- else if (win > 1)
- cout << "Player 2 wins!" << endl;
- }
- return 0;
- }
- void printBoard(char tic[][3]) {
- for (int i = 0; i < 3; i++)
- printf("%c | %c | %c\n", tic[i][0], tic[i][1], tic[i][2]);
- cout << endl;
- }
- void getMove(int turn, int (&xy)[2]) {
- cout << "Player " << (turn%2) + 1 << " go!\nPick the x coordinate of your move: ";
- cin >> xy[0];
- cout << "\nNow input the y: ";
- cin >> xy[1];
- cout << endl;
- }
- void doMove(int &turn, char (&tic)[3][3], int xy[2]) {
- if (tic[xy[1]][xy[0]] != '*') {
- cout << "That space is already taken!" << endl;
- return;
- }
- else if (turn%2 == 0)
- tic[xy[1]][xy[0]] = 'O';
- else if (turn%2 == 1)
- tic[xy[1]][xy[0]] = 'X';
- turn++;
- }
- void checkBoard(int turn, char tic[][3], int &check) {
- if (turn < 5) // not enough turns to declare a winner
- return;
- int p1 = 0;
- int p2 = 0;
- // program checks if any player has won by rows && colums && diagonals
- // rows
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++) {
- if (tic[i][j] == 'O')
- p1++; // score counted every check cycle
- else if (tic[i][j] == 'X')
- p2++;
- }
- if (p1 == 3) { // score of 3 means a player has won
- check = -1;
- return;
- }
- else if (p2 == 3) {
- check = 1;
- return;
- }
- p1 = 0; // score reset after every row/column is checked
- p2 = 0;
- }
- // columns
- for (int j = 0; j < 3; j++) {
- for (int i = 0; i < 3; i++) {
- if (tic[i][j] == 'O')
- p1++;
- else if (tic[i][j] == 'X')
- p2++;
- }
- if (p1 > 2) {
- check = -1;
- cout << "Won by column" << endl;
- return;
- }
- else if (p2 > 2) {
- check = 1;
- cout << "Won by column" << endl;
- return;
- }
- p1 = 0;
- p2 = 0;
- }
- // diags
- if (tic[0][0] == '*' || tic[2][0] == '*'); // no diagonal wins possible
- else if (tic[0][0] == tic[1][1] && tic[1][1] == tic[2][2])
- switch (tic[0][0]) {
- case ('O'): check = -1;
- break;
- case ('X'): check = 1;
- break;
- }
- else if (tic[2][0] == tic[1][1] && tic[1][1] == tic[0][2])
- switch (tic[2][0]) {
- case ('O'): check = -1;
- break;
- case ('X'): check = 1;
- break;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement