Advertisement
DerNerd97

TicTacToe with win detection

May 8th, 2014
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. int x, y, c, i;
  4. int board[3][3]={{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
  5. int display(){
  6.     system("cls");
  7.     for(y = 0; y <= 2; y++){
  8.         for(x = 0; x <= 2; x++){
  9.             switch(board[y][x]){
  10.                 case 0: cout << "[_]";
  11.                         break;
  12.                 case 1: cout << "[X]";
  13.                         break;
  14.                 case 2: cout << "[O]";
  15.                         break;
  16.                 default:cout << "[!]";
  17.             }
  18.         }cout << endl;
  19.     }return 0;
  20. }
  21. int player1(){ //[X]
  22.     cout << "[P1] Enter Y coordinate: ";
  23.     cin >> y;
  24.     cout << "[P1] Enter X coordinate: ";
  25.     cin >> x;
  26.     if(board[y][x] == 0){ board[y][x] = 1; }
  27.     display();
  28.     return 0;
  29. }
  30. int player2(){ //[O]
  31.     cout << "[P2] Enter Y coordinate: ";
  32.     cin >> y;
  33.     cout << "[P2] Enter X coordinate: ";
  34.     cin >> x;
  35.     if(board[y][x] == 0){ board[y][x] = 2; }
  36.     display();
  37.     return 0;
  38. }
  39. int win(){
  40.     for(i = 1; i <= 2; i++){
  41.         for(x = 0; x <= 2; x++){
  42.             if(board[0][x] == i && board[1][x] == i && board[2][x] == i){
  43.                 cout << "P" << i << " won!" << endl;
  44.                 exit;
  45.             }
  46.         }for(x = 0; x <= 2; x++){
  47.             if(board[x][0] == i && board[x][1] == i && board[x][2] == i){
  48.                 cout << "P" << i << " won!" << endl;
  49.                 exit;
  50.             }
  51.         }if(board[0][0] == i && board[1][1] == i && board[2][2] == i){
  52.                 cout << "P" << i << " won!" << endl;
  53.                 exit;
  54.         }if(board[2][0] == i && board[1][1] == i && board[0][2] == i){
  55.                 cout << "P" << i << " won!" << endl;
  56.                 exit;
  57.         }
  58.     }return 0;
  59. }
  60.  
  61. int main() {
  62.     display();
  63.     player1();
  64.     for(c = 0; c <= 3; c++){
  65.         player2();
  66.         win();
  67.         player1();
  68.         win();
  69.     }return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement