Advertisement
heroofhyla

Tic Tac Toe WIP

Oct 3rd, 2014
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <limits>
  3.  
  4. char gameboard[3][3] = {{'7','8','9'},
  5.     {'4','5','6'},
  6.     {'1','2','3'}};
  7. char playerSymbols[] = {'X','O'};
  8. void drawboard();
  9. void processPlayerMove(int);
  10. int getCoord();
  11. int xFromCoord(int coord);
  12. int yFromCoord(int coord);
  13. int main(){
  14.     std::cout << "***TIC TAC TOE***" << std::endl;
  15.     drawboard();
  16.     for (int i = 0; i < 10; i++){
  17.         processPlayerMove(0);
  18.         drawboard();
  19.     }
  20. }
  21.  
  22. void drawboard(){
  23.     for (int i = 0; i < 3; ++i){
  24.         for (int k = 0; k < 3; ++k){
  25.             std::cout << " " << gameboard[i][k];
  26.             if (k < 2){
  27.                 std::cout << " |";
  28.             }
  29.         }
  30.         std::cout << std::endl;
  31.         if (i < 2){
  32.             std::cout << "---+---+---" << std::endl;
  33.         }
  34.     }
  35. }
  36.  
  37. void processPlayerMove(int playerNumber){
  38.     std::cout << "Player " << playerNumber+1 << " choose where to place \'" <<
  39.         playerSymbols[playerNumber] << "\'" << std::endl;
  40.     int targetCoord = getCoord();
  41.     while (gameboard[yFromCoord(targetCoord)][xFromCoord(targetCoord)] != (targetCoord+'0')){
  42.         std::cout << "expected " << targetCoord << " found " <<
  43.         gameboard[yFromCoord(targetCoord)][xFromCoord(targetCoord)] << std::endl;
  44.         std::cout << "That spot is occupied. Please choose another spot." << std::endl;
  45.         targetCoord = getCoord();
  46.     }
  47.     gameboard[yFromCoord(targetCoord)][xFromCoord(targetCoord)] =playerSymbols[playerNumber];
  48. }
  49.  
  50. int getCoord(){
  51.     char userIn;
  52.     do {
  53.         std::cin >> userIn;
  54.     }while (userIn < '0' || userIn > '9');
  55.     std::cin.clear();
  56.     std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
  57.     return userIn-'0';
  58. }
  59.  
  60. int yFromCoord(int coord){
  61.     int zeroedCoord = coord-1;
  62.     zeroedCoord = 8-zeroedCoord;
  63.     return zeroedCoord/3;
  64. }
  65.  
  66. int xFromCoord(int coord){
  67.     int zeroedCoord = coord-1;
  68.     return zeroedCoord%3;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement