Tic-Tac-Toe 2.0
|
00001 00010 #include "tictactoe.h" 00011 #include <iostream> 00012 00013 00014 00015 // TicTacToe 00019 TicTacToe::TicTacToe(void) 00020 { 00021 Reset(); // Reset the game 00022 } 00023 00024 // Reset 00028 void TicTacToe::Reset(void) 00029 { 00030 for (int i=0;i<9;i++) // For each cell 00031 Grid[i]=EMPTY; // put the empty symbol inside 00032 NumMoves=0; // Set the number of moves at zero 00033 } 00034 00035 00036 00037 // DrawGame 00042 void TicTacToe::DrawGame(void) 00043 { 00044 char GridScreen[9]; // Create a copy of the game 00045 for (int i=0;i<9;i++) // For each cell... 00046 { 00047 switch (Grid[i]) // ...analyze the cell 00048 { 00049 case 1 : {GridScreen[i]='X'; break;} // Cross 00050 case 2 : {GridScreen[i]='O'; break;} // Circle 00051 default : {GridScreen[i]=1+i+'0'; break;} // Empty cell (replace by the number of the cell 00052 } 00053 } 00054 // Show the current game in text mode 00055 cout <<" "<<GridScreen[0]<< " | "<< GridScreen[1]<< " | "<< GridScreen[2]<<"\n"; 00056 cout <<" "<<GridScreen[3]<< " | "<< GridScreen[4]<< " | "<< GridScreen[5]<<"\n"; 00057 cout <<" "<<GridScreen[6]<< " | "<< GridScreen[7]<< " | "<< GridScreen[8]<<"\n"; 00058 } 00059 00060 // CurrentPlayer 00066 char TicTacToe::CurrentPlayer(void) 00067 { 00068 return NumMoves%2+1; 00069 } 00070 00071 00072 // Play 00079 char TicTacToe::Play(int NumCell) 00080 { 00081 if (NumCell<1 || NumCell>9) // Check if it is a cell of the grid 00082 return 0; 00083 if (Grid[NumCell-1]!=EMPTY) // Check if th cell is empty 00084 return 0; 00085 00086 Grid[NumCell-1]=NumMoves%2+1; // Place the mark in the grid 00087 History[NumMoves]=NumCell-1; // Memorize for history 00088 NumMoves++; // Increase the number of moves 00089 return 1; // Success 00090 } 00091 00092 // Undo 00096 int TicTacToe::Undo(void) 00097 { 00098 if (NumMoves>=0) 00099 { 00100 NumMoves--; 00101 Grid[History[NumMoves]]=0; 00102 } 00103 return NumMoves; 00104 } 00105 00106 // GameOver 00114 char TicTacToe::GameOver(void) 00115 { 00116 if (Grid[0]==Grid[1] && Grid[1]==Grid[2] && Grid[0]!=EMPTY) return Grid[0]; 00117 if (Grid[3]==Grid[4] && Grid[4]==Grid[5] && Grid[3]!=EMPTY) return Grid[3]; 00118 if (Grid[6]==Grid[7] && Grid[7]==Grid[8] && Grid[6]!=EMPTY) return Grid[6]; 00119 if (Grid[0]==Grid[3] && Grid[3]==Grid[6] && Grid[0]!=EMPTY) return Grid[0]; 00120 if (Grid[1]==Grid[4] && Grid[4]==Grid[7] && Grid[1]!=EMPTY) return Grid[1]; 00121 if (Grid[2]==Grid[5] && Grid[5]==Grid[8] && Grid[2]!=EMPTY) return Grid[2]; 00122 if (Grid[0]==Grid[4] && Grid[4]==Grid[8] && Grid[0]!=EMPTY) return Grid[0]; 00123 if (Grid[2]==Grid[4] && Grid[4]==Grid[6] && Grid[6]!=EMPTY) return Grid[6]; 00124 if (NumMoves==9) return DRAW; 00125 return 0; 00126 }