Staredit Network > Forums > Technology & Computers > Topic: [C++] Tic Tac Toe
[C++] Tic Tac Toe
Sep 11 2011, 2:52 am
By: Sand Wraith  

Sep 11 2011, 2:52 am Sand Wraith Post #1

she/her

I spent the day coding tic tac toe in C++ to help myself get back into the syntax. I didn't comment very much since I was just hacking this together.

Here is an EXE in case you trust me not to destroy your computer: Project1.exe

Code
#include <iostream>

using namespace std;

int field[3][3];
string input;
int coordX, coordY;
bool gameOn = 1;

int inputINT(string prompt)
{
   int n;
   bool bad = 1;
   do
   {
       cout << prompt;
       cin >> n;
       if (cin.fail())
       {
           cout << "ERROR: Invalid input." << endl;
           cin.clear();
           cin.ignore(numeric_limits<int>::max(),'\n');
       }
       else
           bad = 0;
   } while (bad);
   return n;
}

int turn(int player)
{
   bool turn = 1;
   do
   {
       do
       {
           coordX = inputINT("X coordinate: ");
           if (!(coordX >=0 && coordX <= 2))
               cout << "ERROR: Out of range." << endl;
       } while (!(coordX >=0 && coordX <= 2));
       do
       {
           coordY = inputINT("Y coordinate: ");
           if (!(coordY >=0 && coordY <= 2))
               cout << "ERROR: Out of range." << endl;
       } while (!(coordY >=0 && coordY <= 2));
       if (field[coordX][coordY] == 0)
       {
          field[coordX][coordY] = player;
          turn = 0;
       }
       else
           cout << "ERROR: Cannot place marker there." << endl;
   } while (turn);
}

int result()
{
   return 0;
}

void clrScrn()
{
    for (int i = 0; i < 50; i++)
    {
        cout << endl;
    }
}

void printField()
{
    cout << "  0 1 2" << endl;
    for (int x = 0; x < 3; x++)
    {
          cout << x << " ";
          for (int y = 0; y < 3; y++)
          {
              switch (field[y][x])
              {
                     case 0:
                          cout << "- ";
                          break;
                     case 1:
                          cout << "X ";
                          break;
                     case 10:
                          cout << "O ";
                          break;
              }
          }
          cout << endl;
    }
}

int winChk(int sum)
{
   if (sum == 3)
   {
       cout << "Player 1 wins!" << endl;
       return 1; // p1 win
   }
   if (sum == 30)
   {
       cout << "Player 2 wins!" << endl;
       return 10; // p2 win
   }
   return 0;
}

int gameState()
{
   int sum, r;
   for (int x = 0; x < 3; x++) //check rows
   {
       sum = 0;
       for (int y = 0; y < 3; y++)
       {
           sum += field[x][y];
           r = winChk(sum);
           if (r != 0)
               return r;
       }
   }
   for (int x = 0; x < 3; x++) // check columns
   {
       sum = 0;
       for (int y = 0; y < 3; y++)
       {
           sum += field[y][x];
           r = winChk(sum);
           if (r != 0)
               return r;
       }
   }
   sum = 0; //check diagonal 1
   for (int x = 0; x < 3; x++)
       sum += field[x][x];
   r = winChk(sum);
   if (r != 0)
       return r;
   sum = 0; //check diagonal 2
   for (int x = 2; x >= 0; x--)
           sum += field[x][2-x];
   r = winChk(sum);
   if (r != 0)
       return r;
   return 0; // continue
}

int main()
{
   while (gameOn)
   {
       if (gameState() == 0)
       {
           clrScrn();
           printField();
           cout << endl;
           cout << "Player 1" << endl;
           turn(1);
       }
       else
           gameOn = 0;
       clrScrn();
       printField();
       if (gameState() == 0)
       {
           cout << endl;
           cout << "Player 2" << endl;
           turn(10);
       }
       else
           gameOn = 0;
   }
   cout << endl;
   system("PAUSE");
   return EXIT_SUCCESS;
}





Sep 12 2011, 2:50 am BiOAtK Post #2



You have no tied game result, which is pretty key in tic-tac-toe. Other than that, it works fine. I actually am going to look through this code, as I am trying to learn C++ and I think i'll try to emulate it.
Maybe make it read a coordinate as an ordered pair? (0,0) for example.



None.

Sep 12 2011, 3:38 am Lanthanide Post #3



Instead of having a loop to calculate the game state, you could just record the sum of each row and column and diagonal when the players input their symbols. Standard memory vs time tradeoff. This would become considerably more efficient if you went to a 4x4 board for example (linear memory increase vs exponential time increase).

There's no need to calculate the game state when less than 5 turns have occurred, because there'll only be 2 marks for each player on the board and therefore no one can win until turn 5 at the earliest.

Extending the program so the player can choose the board size would be neat (from 2x2 up to 10x10 for example).



None.

Sep 12 2011, 5:04 am shmeeps Post #4



Just a few nit-picky things:

Include <string> at the top. Some compilers (VS 2010, for example) have trouble pushing strings into the output stream without it. If you copy and paste the code from here to there, it won't compile until it's added.
Turn() should be of type void, since you never return anything from it, nor do you really have any functionality for returning.

There's definitely some efficiency problems you could improve on, but solid overall, save for what's already been stated.



None.

Sep 12 2011, 6:15 am Lanthanide Post #5



Also this isn't C++ so much as it is C with C++ syntax (cout mainly).

When you bring some objects in, then it'll really be C++.



None.

Sep 12 2011, 6:28 am O)FaRTy1billion[MM] Post #6

👻 👾 👽 💪

Quote from Lanthanide
Also this isn't C++ so much as it is C with C++ syntax (cout mainly).

When you bring some objects in, then it'll really be C++.
Why I, personally, just use C. :awesome:



TinyMap2 - Latest in map compression! ( 7/09/14 - New build! )
EUD Action Enabler - Lightweight EUD/EPD support! (ChaosLauncher/MPQDraft support!)
EUDDB - topic - Help out by adding your EUDs! Or Submit reference files in the References tab!
MapSketch - New image->map generator!
EUDTrig - topic - Quickly and easily convert offsets to EUDs! (extended players supported)
SC2 Map Texture Mask Importer/Exporter - Edit texture placement in an image editor!
\:farty\: This page has been viewed [img]http://farty1billion.dyndns.org/Clicky.php?img.gif[/img] times!

Options
  Back to forum
Please log in to reply to this topic or to report it.
Members in this topic: None.
[2024-5-02. : 1:19 pm]
Vrael -- IM GONNA MANUFACTURE SOME SPORTBALL EQUIPMENT WHERE THE SUN DONT SHINE BOY
[2024-5-02. : 1:35 am]
Ultraviolet -- Vrael
Vrael shouted: NEED SOME SPORTBALL> WE GOT YOUR SPORTBALL EQUIPMENT MANUFACTURING
Gonna put deez sportballs in your mouth
[2024-5-01. : 1:24 pm]
Vrael -- NEED SOME SPORTBALL> WE GOT YOUR SPORTBALL EQUIPMENT MANUFACTURING
[2024-4-30. : 5:08 pm]
Oh_Man -- https://youtu.be/lGxUOgfmUCQ
[2024-4-30. : 7:43 am]
NudeRaider -- Vrael
Vrael shouted: if you're gonna link that shit at least link some quality shit: https://www.youtube.com/watch?v=uUV3KvnvT-w
Yeah I'm not a big fan of Westernhagen either, Fanta vier much better! But they didn't drop the lyrics that fit the situation. Farty: Ich bin wieder hier; nobody: in meinem Revier; Me: war nie wirklich weg
[2024-4-29. : 6:36 pm]
RIVE -- Nah, I'm still on Orange Box.
[2024-4-29. : 4:36 pm]
Oh_Man -- anyone play Outside the Box yet? it was a fun time
[2024-4-29. : 12:52 pm]
Vrael -- if you're gonna link that shit at least link some quality shit: https://www.youtube.com/watch?v=uUV3KvnvT-w
[2024-4-29. : 11:17 am]
Zycorax -- :wob:
[2024-4-27. : 9:38 pm]
NudeRaider -- Ultraviolet
Ultraviolet shouted: NudeRaider sing it brother
trust me, you don't wanna hear that. I defer that to the pros.
Please log in to shout.


Members Online: UndeadStar, Enfie