#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
// Constants for the game
const int GRID_SIZE = 4; // 4x4 grid
const int NUM_PAIRS = (GRID_SIZE * GRID_SIZE) / 2;
// Function prototypes
void initializeBoard(std::vector<std::vector<char>>& board, std::vector<std::vector<char>>& displayBoard);
void displayBoard(const std::vector<std::vector<char>>& board, const std::vector<std::vector<char>>& displayBoard);
bool isMatch(const std::vector<std::vector<char>>& board, int x1, int y1, int x2, int y2);
bool isBoardComplete(const std::vector<std::vector<char>>& displayBoard);
int main() {
std::vector<std::vector<char>> board(GRID_SIZE, std::vector<char>(GRID_SIZE));
std::vector<std::vector<char>> displayBoard(GRID_SIZE, std::vector<char>(GRID_SIZE, '*'));
initializeBoard(board, displayBoard);
int x1, y1, x2, y2;
bool matched;
int attempts = 0;
while (!isBoardComplete(displayBoard)) {
displayBoard(displayBoard, displayBoard);
std::cout << "Enter coordinates of the first card (row and column): ";
std::cin >> x1 >> y1;
std::cout << "Enter coordinates of the second card (row and column): ";
std::cin >> x2 >> y2;
if (x1 < 0 || x1 >= GRID_SIZE || y1 < 0 || y1 >= GRID_SIZE ||
x2 < 0 || x2 >= GRID_SIZE || y2 < 0 || y2 >= GRID_SIZE ||
(x1 == x2 && y1 == y2)) {
std::cout << "Invalid input. Try again.\n";
continue;
}
if (isMatch(board, x1, y1, x2, y2)) {
std::cout << "It's a match!\n";
displayBoard[x1][y1] = board[x1][y1];
displayBoard[x2][y2] = board[x2][y2];
} else {
std::cout << "Not a match. Try again.\n";
}
attempts++;
}
displayBoard(displayBoard, displayBoard);
std::cout << "Congratulations! You matched all pairs in " << attempts << " attempts.\n";
return 0;
}
void initializeBoard(std::vector<std::vector<char>>& board, std::vector<std::vector<char>>& displayBoard) {
std::vector<char> cards;
for (int i = 0; i < NUM_PAIRS; ++i) {
cards.push_back('A' + i);
cards.push_back('A' + i);
}
std::srand(std::time(0));
std::random_shuffle(cards.begin(), cards.end());
for (int i = 0; i < GRID_SIZE; ++i) {
for (int j = 0; j < GRID_SIZE; ++j) {
board[i][j] = cards[i * GRID_SIZE + j];
}
}
}
void displayBoard(const std::vector<std::vector<char>>& board, const std::vector<std::vector<char>>& displayBoard) {
std::cout << " ";
for (int j = 0; j < GRID_SIZE; ++j) {
std::cout << j << ' ';
}
std::cout << '\n';
for (int i = 0; i < GRID_SIZE; ++i) {
std::cout << i << ' ';
for (int j = 0; j < GRID_SIZE; ++j) {
std::cout << displayBoard[i][j] << ' ';
}
std::cout << '\n';
}
}
bool isMatch(const std::vector<std::vector<char>>& board, int x1, int y1, int x2, int y2) {
return board[x1][y1] == board[x2][y2];
}
bool isBoardComplete(const std::vector<std::vector<char>>& displayBoard) {
for (int i = 0; i < GRID_SIZE; ++i) {
for (int j = 0; j < GRID_SIZE; ++j) {
if (displayBoard[i][j] == '*') {
return false;
}
}
}
return true;
}