Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created March 30, 2023 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codecademydev/312f89e78c1d9616e0d78b78eb4408d5 to your computer and use it in GitHub Desktop.
Save codecademydev/312f89e78c1d9616e0d78b78eb4408d5 to your computer and use it in GitHub Desktop.
Codecademy export
#include <iostream>
#include "ttt_f.cpp"
using namespace std;
int main()
{
char board[3][3] = {{'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
int row, col;
char player1 = 'X', player2 = 'O';
char currentPlayer = player1;
bool gameFinished = false;
cout << "Tic Tac Toe Game Best of 5\n\n";
cout << "Player 1: " << player1 << "\nPlayer 2: " << player2 << "\n\n";
// Game loop
for (int i = 0; i < 5; i++)
{
while (!gameFinished)
{
// Print current board
cout << "Current board:\n";
display_board(board);
// Take input from current player
cout << "Player " << currentPlayer << " enter row and column (e.g. 1 2): ";
cin >> row >> col;
// Check if input is valid
if (row < 1 || row > 3 || col < 1 || col > 3)
{
cout << "Invalid input. Please enter a row and column between 1 and 3.\n";
continue;
}
if (board[row - 1][col - 1] != '-')
{
cout << "Invalid input. That cell is already occupied.\n";
continue;
}
// Update the board
board[row - 1][col - 1] = currentPlayer;
currentPlayer = (currentPlayer == player1) ? player2 : player1;
// Check if the game is over
win_c(gameFinished, board);
}
}
return 0;
}
#include <iostream>
#include <vector>
void display_board(char board[3][3])
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
std::cout << board[i][j] << " ";
}
std::cout << "\n";
}
}
void win_c(bool gameFinished, char board[3][3])
{
bool isWin = false;
char player1 = 'X', player2 = 'O';
char currentPlayer = player1;
for (int i = 0; i < 3; i++)
{
if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer)
{
isWin = true;
break;
}
if (board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer)
{
isWin = true;
break;
}
}
if (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer)
{
isWin = true;
}
if (board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer)
{
isWin = true;
}
if (isWin)
{
std::cout << "Player " << currentPlayer << " wins!\n";
gameFinished = true;
}
else
{
// Check if the game is a tie
bool isTie = true;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i][j] == '-')
{
isTie = false;
break;
}
}
if (!isTie)
{
break;
}
}
if (isTie)
{
std::cout << "The game is a tie.\n";
gameFinished = true;
}
else
{// Switch players
currentPlayer = (currentPlayer == player1) ? player2 : player1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment