Tic-Tac-Toe Challenge Project (C++)

Here’s my project:

I have had help from ChatGpt to correct the logic errors.

i spent the entrety of my day friday and saturday trying to understand how to get this to work.
fixing all kinds of errors and i finally did it. without help. im excited to share this with others because i never been so happy to finish any project ever.
ive noticed other projects uses different types of functions and syntax than mine, i only know and use what codecademy has taught me

Hey guys!

This is my second project here, after the Text Adventure one.
I have also seen that a lot people write a lot of different types of code, I have only use what I learned on Codecademy until now. I haven’t managed to make it restart, but everything else works, including not letting the player write over another player’s symbol.
It does however go in an infinite loop if you write anything other than a number from 1 to 9 when playing haha. Looking forward to suggestions!

I wrote mine to keep the score and iterate to the next game if the user inputs that they wish to continue playing. The game also switches who is X and who is O every round to keep the game fair.

Here’s my solution. Please let me know how it could be improved! Hopefully this is of help to someone.

hope you like it

This was a challenge (and I had to learn not to try and change a vector from within a function, something which still messes with my brain even now)

https://github.com/esapuolakka/tic_tac_toe.git

ttt.cpp

#include
#include
#include “ttt.hpp”

using namespace std;

int main()
{

bool names = true;

bool game;

// Player input
int cell;

// Player points & names
int x_points = 0;
int o_points = 0;

// The turns of the game (total 9 turns)
int turn;

string player_x;
string player_o;

welcome();

do {
cout << “player X, write your name: \n”;
getline(cin, player_x);

cout << "player O, write your name: \n";
getline(cin, player_o);

} while (player_x == “” || player_o == “”);

while(true)
{
turn = 1;

// Player turn
char current_player = ‘X’;

// Reset the board
char board = {‘1’,‘2’,‘3’,‘4’,‘5’,‘6’,‘7’,‘8’,‘9’};

// Player choice the play or not
char play;

cout << “\nStart the game? (press ‘y’ to play, any else to quit)\n”;
cin >> play;

play = toupper(play);

if (play == ‘Y’)
{
game = true;
}
else
{
return 0;
}

bool single_game = true;

while (single_game)
{
show_board(board);


// Input from the current player
cout << "\nPlayer " << current_player << ". Choose a cell by entering a number (1-9): \n";
cin >> cell;


// Convert input to 0-based index
cell--;


// Check is a chosen cell empty
if (board[cell] == 'X' || board[cell] == 'O')
{
    cout << "The cell is already taken. Choose another one!\n";
    continue;
}


// Update the board
board[cell] = current_player;


// Win check
if (check_win(board, current_player, x_points, o_points))
{
    show_board(board);
    cout << endl;
    cout << "Player " << current_player << " Won!\n";
    cout << endl;

    single_game = false;
}

// Tie check
if (turn == 9)
{
    cout << endl;
    cout << "The game is tie!\n";
    
    single_game = false;
}

// Switch player
if (current_player == 'X')
{
    current_player = 'O';
}
else if (current_player == 'O')
{
    current_player = 'X';
}

    turn++;
}

cout << "Player X: " << player_x << " points: " << x_points;
cout << "\t\tPlayer O: " << player_o << " points: " << o_points << "\n";
cout << endl;

}

cout << “Thank you for playing!\n”;
cout << endl;

return 0;
}

ttt.hpp

void welcome();
void show_board(char board);
bool check_win(char board, char current_player, int& x_points, int& o_points);

ttt_functions

#include

using namespace std;

void welcome()
{
cout << endl;
cout << “============================\n”;
cout << “===== TIC TAC TOE Game =====\n”;
cout << “============================\n”;
cout << endl;
}

void show_board(char board)
{
cout << board[0] << “|” <<board[1] << “|” << board[2] << endl;
cout << board[3] << “|” <<board[4] << “|” << board[5] << endl;
cout << board[6] << “|” <<board[7] << “|” << board[8] << endl;
}

bool check_win(char board, char current_player, int& x_points, int& o_points)
{
// vertical check
for (int i = 0; i < 3; i++)
{
if (board[i] == current_player && board[i+3] == current_player && board[i+6] == current_player)
{
if (current_player == ‘X’)
{
x_points++;
}
else
{
o_points++;
}
return true;

    }
}
// horizontal check
for (int i = 0; i < 9; i += 3)
{
    if (board[i] == current_player && board[i+1] == current_player && board [i+2] == current_player)
    {
        if (current_player == 'X')
        {
            x_points++;
        }
        else
        {
            o_points++;
        }
        return true;
    }
}
// diagonal check
for (int i = 0; i < 9; i++)
{
    if (board[0] == current_player && board[4] == current_player && board[8] == current_player)
    {
        if (current_player == 'X')
        {
            x_points++;
        }
        else
        {
            o_points++;
        }
        return true;
    }
    else if (board[2] == current_player && board[4] == current_player && board[6] == current_player)
    {
        if (current_player == 'X')
        {
            x_points++;
        }
        else
        {
            o_points++;
        }
        return true;
    }
}
return false;

}

Here is an implementation using the built-in find function in the winner criterion:

Let me know what you think guys.

Here’s my solution. Would love to hear any feedback! Thanks!

Main Code
Header File
Functions

My poor codes.
It took two weeks to accomplish this objective.

Lot of fun

#include <iostream>
#include <vector>

//ASCII values('x'=120  'o'= 111  .'=46)


bool availablePositionChecker(char grid[3][3], int row, int column) {

   if (int(grid[row][column]) != 111 && int(grid[row][column]) != 120)
      return true;
   else
      return false;
}

std::vector<int> positionChoiceP1(char grid[3][3]){
   
   bool valid = false;
   bool available = false;
   std::vector<int> positionPlayer = {1};
   int row;
   int column;

   
   while (valid == false) {
      do {
         std::cout << ":::Player one turn:::" << "\n";
         std::cout << ":::::::::::::::::::::" << "\n";
         
         std::cout << "\n" << "Enter your row position: ";
         std::cin >> row;
         std::cout << "Enter your column position: ";
         std::cin >> column;
         if (row >= 0 && row <= 2 && column >= 0 && column <= 2) {
            valid = true;
            available = availablePositionChecker(grid, row, column);
         } else {
            std::cout << "This position is not valid, try again" << "\n";
         }
      } while (available == false);
   }

   positionPlayer.push_back(row);
   positionPlayer.push_back(column);
   return positionPlayer;
}

std::vector<int> positionChoiceP2(char grid[3][3]){
   
   bool valid = false;
   bool available = false;
   std::vector<int> positionPlayer = {2};
   int row;
   int column;

   while (valid == false) {
      do {
         std::cout << ":::Player two turn:::" << "\n";
         std::cout << ":::::::::::::::::::::" << "\n";
         
         std::cout << "\n" << "Enter your row position: ";
         std::cin >> row;
         std::cout << "Enter your column position: ";
         std::cin >> column;
         if (row >= 0 && row <= 2 && column >= 0 && column <= 2) {
            valid = true;
            available = availablePositionChecker(grid, row, column);
         } else {
            std::cout << "This position is not valid, try again" << "\n";
         }
      } while (available == false);
   }
   positionPlayer.push_back(row);
   positionPlayer.push_back(column);
   return positionPlayer;
}

void displayGrid(char grid[3][3]){
   std::cout << "\n --------- " << "\n";
   for(int j= 0; j<3; j++){
      if(j!= 0){
         std::cout << "\n";
      }
      for(int i= 0; i<3; i++){
         if (i == 0) {
            std::cout << "| " << grid[j][i] << " ";
         }else if (i == 2) {
            std::cout << " " << grid[j][i] << " |";
         } else {
            std::cout << " " << grid[j][i] << " ";
         }
      }
   }
   std::cout << "\n --------- " << "\n";
   std::cout << "\n";
}

bool rowsChecker(char grid[3][3]) {
   bool win = false;
   int accumulatorASCII = 0;

   for(int j= 0; j< 3; j++) {
      for(int i= 0; i< 3; i++) {
         accumulatorASCII += (int)grid[j][i];
         //std::cout << "accumulator is " << accumulatorASCII << "\n";
      }
      if((accumulatorASCII/3) == 120 || (accumulatorASCII/3) == 111)
         win = true;
      accumulatorASCII = 0;
   }
   return win;
}

bool columnsChecker(char grid[3][3]) {
   bool win = false;
   int accumulatorASCII = 0;

   for(int j= 0; j< 3; j++) {
      for(int i= 0; i< 3; i++) {
         accumulatorASCII += (int)grid[i][j];
         //std::cout << "accumulator is " << accumulatorASCII << "\n";
      }
      if((accumulatorASCII/3) == 120 || (accumulatorASCII/3) == 111)
         win = true;
      accumulatorASCII = 0;
   }
   return win;
}

bool diagonalsChecker(char grid[3][3]) {
   bool win = false;
   int accumulatorASCII = 0;
   
   accumulatorASCII = (int)grid[0][0] + (int)grid[1][1] + (int)grid[2][2] ;
   if((accumulatorASCII/3) == 120 || (accumulatorASCII/3) == 111)
      win = true;
   accumulatorASCII = (int)grid[0][2] + (int)grid[1][1] + (int)grid[2][0] ;
   if((accumulatorASCII/3) == 120 || (accumulatorASCII/3) == 111)
      win = true;
   
   return win;
}

bool updateGrid(char grid[3][3], std::vector<int> positions){
   bool win = false;
   std::vector<int> checker;
   int accumulatorASCII = 0;
   int player = positions[0];
   int row = positions[1];
   int col = positions[2];

   if (player == 1)
      grid[row][col] = 'x';
   else
      grid[row][col] = 'o';

   
   win = rowsChecker(grid);
   if (!win)
      win = columnsChecker(grid);
      if (!win)
         win = diagonalsChecker(grid);
   
   displayGrid(grid);
   return win;
}

int main(){

   //Grid declaration
   char grid[3][3]= {{'.', '.', '.'}, {'.', '.', '.'}, {'.', '.', '.'}};
   bool isWinP1 = false;
   bool isWinP2 = false;
   std::vector<int> rowColP1;
   std::vector<int> rowColP2;
   

   while(true){
      rowColP1 = positionChoiceP1(grid);
      isWinP1 = updateGrid(grid, rowColP1);
      if (isWinP1) {
         std::cout <<  "Player1 Won!";
         break;
      }
      
      rowColP2 = positionChoiceP2(grid);
      isWinP2 = updateGrid(grid, rowColP2);
      if (isWinP2) {
         std::cout <<  "Player2 Won!";
         break;
      }
   }
}

I’m truly having a hard time getting started here. Storing and outputting the 3x3 grid with empty spaces that are updated via user input along the way in turns… I feel I’m not fully equipped for the challenge even after completing the previous lessons and projects. I skimmed through the solution and saw code I did not recognize from the lessons like cin.clear(). I’ve gone back through the module practices for loops, functions, and vectors, and still just find myself lost. Any help would be greatly appreciated!

Now I just can’t get a bool checkwin() function to store properly so I can output winner if checkwin() == true.

Hi, If you haven’t figured this out yet. I used for loops that iterated over the vector every turn to check if there are three X’s or O’s in a row. The check win function doesn’t necessarily need to “store” anything, but your vector does need to store the X’s and O’s.

The if statement would look like something similar to this:
if(checkwin(parameters)) {output}
Because the if statement is already checking for a true value in order to execute.

Hello All! I’ve completed my TicTacToe game. Feel free to test it out, and to leave any feedback thanks!
https://github.com/ReeceB98/TicTacToe

Here is my solution! Let me know if you would have done anything different.

Hi friends, my solution is below. I got a little fancy with some sorting imports I found, and then printing the actual gameboard I had a specific way I wanted it to look so the code is super ugly but functionality is there. Feel free to reach out with suggestions or questions~

My code. Not as modular as the accepted solution, but gives a chess like grid implementation for input and uses std::vectors

This is eye cancer