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.
[03:34 pm]
ManCubuS -- Used : " [img=https://i.imgur.com/gpOjTuD.jpeg] "
[03:28 pm]
ManCubuS -- Even tried with imgur, doesn't attach.
[03:14 pm]
ManCubuS -- I should try a workaround, thanks! Sadly imgur is blocked in my country for some unknown reason.
[03:05 pm]
NudeRaider -- I think SEN has trouble with https or hotlinking is forbidden. It certainly is nothing about the size, it just fails to get any size. You can get it working if you use imgur and include the actual image link for the img tag. Like this: [img=https://i.imgur.com/ddYqXZa.jpeg]
[11:15 am]
ManCubuS -- Hey fellas! Anyone knows why when I try to upload an image it says "failed to get image size"? I even tried making it so small. Imgur isn't working here and I tried postimg no luck.
[2026-7-23. : 6:40 am]
Oh_Man -- true
[2026-7-23. : 3:16 am]
RIVE -- Still annoyed there was never a trigger to stop or pause wavs.
[2026-7-23. : 1:40 am]
Oh_Man -- tthen u come to SCBW and it's like - upload WAV, play WAV.... sigh why cant it be that easy
[2026-7-23. : 1:40 am]
Oh_Man -- and no consistent easy to use way to then play the audio either
[2026-7-23. : 1:39 am]
Oh_Man -- where they use third party audioprogram called WWISE which basically makes adding audio extremely difficult
Please log in to shout.


Members Online: ManCubuS, Dem0n