Advertisement
Guest User

Untitled

a guest
Aug 24th, 2009
422
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. void DrawGrid(char szBoxes[]){
  6.     cout << "-------" << endl;
  7.     for(int i = 0; i < 3; i++) //Loop for rows
  8.     {
  9.         cout << "|";
  10.         for(int ii = i*3; ii < ((i+1)*3); ii++)//Loop for columns
  11.             cout << szBoxes[ii] << "|";
  12.         cout << endl << "-------" << endl;
  13.     }
  14. }
  15.  
  16. bool AWinner(char szBoxes[])
  17. {
  18.     for(int i = 0; i < 3; i ++)
  19.     {
  20.         if(szBoxes[i] == szBoxes[i+1] && szBoxes[i+1] == szBoxes[i+2])//Return true for a full row
  21.             return true;
  22.         else if(szBoxes[i] == szBoxes[i+3] && szBoxes[i+3] == szBoxes[i+6])//Return true for full column
  23.             return true;
  24.         else if(i == 0)
  25.         {
  26.             if(szBoxes[0] == szBoxes[4] && szBoxes[4] == szBoxes[8])//Diagonal t left to b right
  27.                 return true;
  28.         }
  29.         else if(i == 2)
  30.         {
  31.             if(szBoxes[2] == szBoxes[4] && szBoxes[4] == szBoxes[6])//Diagonal t right to b left
  32.                 return true;
  33.         }
  34.     }
  35.     return false;
  36. }
  37.  
  38. int main()
  39. {
  40.     char chPlayer = 'X'; // Holds the appropriate character for the current player
  41.     char chInput = NULL;
  42.     int nInput = 0;
  43.     cout << "NOUGHTS AND CROSSES" << endl;
  44.     while(true){
  45.         cout << "Enter any key to start a new game." << endl;
  46.         cin >> chInput;
  47.         bool bWinner = false;
  48.         char szBoxes[] = "012345678";
  49.         int nTurn = 1; //1 or 2
  50.         DrawGrid(szBoxes);    //Draw the initial grid
  51.         while(!bWinner)
  52.         {
  53.             cout << "Player " << nTurn << " pick a box." << endl;
  54.             while(true)
  55.             {
  56.                 cin >> nInput;
  57.                 if(szBoxes[nInput] != 'X' && szBoxes[nInput] != 'Y')
  58.                     break;
  59.                 cout << "Box has already been played, please choose another." << endl;
  60.             }
  61.             szBoxes[nInput] = (nTurn == 1) ? 'X' : 'O';//Player 1 is X. Player 2 is O.
  62.             DrawGrid(szBoxes);
  63.             if(AWinner(szBoxes))
  64.                 break;
  65.             nTurn = (nTurn == 1) ? 2 : 1;
  66.         }
  67.         cout << "Player " << nTurn << " wins." << endl;
  68.     }
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement