0% found this document useful (0 votes)
18 views

game coding

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

game coding

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

#include <iostream>

#include <vector>
#include <limits>
#include <cstdlib>
#include <ctime>
#include <string>
#include <algorithm> // Include this for std::all_of
using namespace std;

// ANSI color codes


const string RESET = "\033[0m";
const string BLUE = "\033[34m"; // Blue for X
const string RED = "\033[31m"; // Red for O
const string YELLOW = "\033[33m"; // Yellow for result message
const string WHITE = "\033[37m"; // White for text

// Function prototypes
void displayBoard(const vector<vector<string>>& board);
bool isWin(const vector<vector<string>>& board, char player);
bool isDraw(const vector<vector<string>>& board);
void makeMove(vector<vector<string>>& board, char player);
void makeAIMove(vector<vector<string>>& board, const string& difficulty);
void clearScreen();
bool playAgain();
string getAIDifficulty();
int chooseGameMode();

// Main function
int main() {
srand(static_cast<unsigned>(time(0))); // Seed for random AI moves

do {
clearScreen();
cout << YELLOW << "*********************\n";
cout << "* Tic Tac Your Toe! *\n";
cout << "*********************\n";
cout << "Type Enter to start the game...\n";
cin.ignore(); // Wait for Enter key to start the game

// Choose game mode


int gameMode = chooseGameMode();
string aiDifficulty;
if (gameMode == 1) { // Single Player
aiDifficulty = getAIDifficulty();
}

// Fixed board size (6x6)


const int boardSize = 6;
vector<vector<string>> board(boardSize, vector<string>(boardSize));
char currentPlayer = 'X';
bool gameOver = false;

// Initialize board with numbers 1-36


int cellNumber = 1;
for (int i = 0; i < boardSize; ++i) {
for (int j = 0; j < boardSize; ++j) {
board[i][j] = to_string(cellNumber++);
}
}
while (!gameOver) {
clearScreen();
displayBoard(board);

if (gameMode == 2 || currentPlayer == 'X') {


makeMove(board, currentPlayer); // Human move
} else {
cout << "Opponent is making a move...\n";
makeAIMove(board, aiDifficulty); // AI move
}

if (isWin(board, currentPlayer)) {
clearScreen();
displayBoard(board);
cout << YELLOW << "Player " << currentPlayer << " wins!" << RESET
<< "\n";
gameOver = true;
} else if (isDraw(board)) {
clearScreen();
displayBoard(board);
cout << YELLOW << "It's a draw!" << RESET << "\n";
gameOver = true;
} else {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X'; // Switch
player
}
}
} while (playAgain());

cout << YELLOW << "Thanks for playing! Goodbye!" << RESET << "\n";
return 0;
}

// Display the current game board


void displayBoard(const vector<vector<string>>& board) {
cout << "\n";
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[i].size(); ++j) {
if (board[i][j] == "X") {
cout << BLUE << " X " << RESET;
} else if (board[i][j] == "O") {
cout << RED << " O " << RESET;
} else {
// Right-align single-digit numbers for consistency
if (board[i][j].length() == 1) {
cout << WHITE << " " << board[i][j] << " " << RESET;
} else {
cout << WHITE << board[i][j] << " " << RESET;
}
}

if (j < board[i].size() - 1) cout << "|"; // Vertical separator


}
cout << "\n";
if (i < board.size() - 1) {
cout << string(board[i].size() * 4 - 1, '-') << "\n"; // Horizontal
separator
}
}
cout << "\n";
}

// Check if the given player has won


bool isWin(const vector<vector<string>>& board, char player) {
int size = board.size();

// Check rows and columns


for (int i = 0; i < size; ++i) {
if (all_of(board[i].begin(), board[i].end(), [player](const string& c)
{ return c == string(1, player); })) return true;
if (all_of(board.begin(), board.end(), [player, i](const vector<string>&
row) { return row[i] == string(1, player); })) return true;
}

// Check diagonals
if (all_of(board.begin(), board.end(), [player, n = 0](const vector<string>&
row) mutable { return row[n++] == string(1, player); })) return true;
if (all_of(board.begin(), board.end(), [player, n = size - 1](const
vector<string>& row) mutable { return row[n--] == string(1, player); })) return
true;

return false;
}

// Check if the board is full and no winner (draw)


bool isDraw(const vector<vector<string>>& board) {
for (const auto& row : board) {
for (const auto& cell : row) {
if (cell != "X" && cell != "O") return false;
}
}
return true;
}

// Allow the current player to make a move


void makeMove(vector<vector<string>>& board, char player) {
int choice;
bool validMove = false;

while (!validMove) {
cout << "Player " << player << ", enter a number to make your move (1-36):
";

// Validate input is a number


while (!(cin >> choice)) {
cin.clear(); // Clear the invalid input
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Discard input
cout << "Invalid input. Please enter a valid number: ";
}

int size = board.size(); // Get board size dynamically


if (choice >= 1 && choice <= size * size) { // Ensure choice is within
range
int row = (choice - 1) / size;
int col = (choice - 1) % size;

if (board[row][col] != "X" && board[row][col] != "O") { // Check if


cell is free
board[row][col] = string(1, player); // Make the move
validMove = true;
} else {
cout << "That cell is already taken. Try again.\n";
}
} else {
cout << "Invalid move. Enter a number between 1 and 36.\n";
}
}
}

// AI makes a random move


void makeAIMove(vector<vector<string>>& board, const string& difficulty) {
int size = board.size();
vector<pair<int, int>> availableMoves;

// Collect all available moves


for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
if (board[i][j] != "X" && board[i][j] != "O")
availableMoves.emplace_back(i, j);

if (availableMoves.empty()) return;

// AI logic (currently random)


pair<int, int> aiMove = availableMoves[rand() % availableMoves.size()];

board[aiMove.first][aiMove.second] = "O";
}

// Clear the console screen


void clearScreen() {
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}

// Ask for the AI difficulty level


string getAIDifficulty() {
string difficulty;
cout << "Choose difficulty (Easy, Medium, Hard): ";
while (!(cin >> difficulty) || (difficulty != "Easy" && difficulty != "Medium"
&& difficulty != "Hard")) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << " ";
}
return difficulty;
}

// Ask for the game mode


int chooseGameMode() {
int mode;
cout << "Choose game mode:\n";
cout << "1. Single Player \n";
cout << "2. Double Player \n";
cout << "Enter 1 for Single Player or 2 for Double Player: ";
while (!(cin >> mode) || (mode != 1 && mode != 2)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << " ";
}
return mode;
}

// Ask if players want to play again


bool playAgain() {
char choice;
cout << "Do you want to play again? (y/n): ";
while (!(cin >> choice) || (choice != 'y' && choice != 'n')) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please enter 'y' or 'n': ";
}
return choice == 'y';
}

You might also like