1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
|
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
constexpr int BoardSize {6};
class memoryGame6 {
private:
int cards[BoardSize][BoardSize] {};
char face[BoardSize][BoardSize] {};
int pairs[BoardSize * BoardSize] {1, 1, 2, 2, 3, 3,
4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9,
10, 10, 11, 11, 12, 12,
13, 13, 14, 14, 15, 15,
16, 16, 17, 17, 18, 18};
void dopick(int& x, int&y) {
bool bad {};
do {
bad = false;
std::cout << "\nEnter the row (1 to " << BoardSize << ") and col (1 to " << BoardSize << ") position of the pair : ";
std::cin >> x >> y;
// Changing input from 1-4 to 0-3 for array
--x;
--y;
// Checking invalid position
bad = (x < 0 || x >= BoardSize || y < 0 || y >= BoardSize) && (std::cout << "\nInvalid position.\n");
if (!bad)
bad = face[x][y] != '*' && (std::cout << "\nCard at this position already faced up. Select option again.\n");
} while (bad);
face[x][y] = "0123456789ABCDEFGHIJ"[cards[x][y]];
table();
}
// For displaying shuffled cards (faced up and faced down)
void table() {
std::cout << '\n';
for (int i = 0; i < BoardSize; i++) {
for (int j = 0; j < BoardSize; j++)
std::cout << face[i][j] << " ";
std::cout << '\n';
}
}
void shuffle() {
int required {BoardSize * BoardSize};
// Run until all cards are shuffle
while (required) {
// Random pick of array index
const auto x {rand() % BoardSize};
const auto y {rand() % BoardSize};
// Checking if array index is empty or not
if (cards[x][y] == 0)
cards[x][y] = pairs[--required];
}
}
// Function to let player pick cards through index position
void pick() {
int x1 {}, x2 {}, y1 {}, y2 {};
dopick(x1, y1);
dopick(x2, y2);
// Checking either pair matched or not
if (face[x1][y1] == face[x2][y2])
std::cout << "\nPair matched.\n";
else {
std::cout << "\nPair do not match. Select again!\n";
face[x1][y1] = face[x2][y2] = '*';
}
}
// Checking either all cards are shuffled or not
bool win() {
for (int i = 0; i < BoardSize; ++i)
for (int j = 0; j < BoardSize; ++j)
if (face[i][j] == '*')
return false;
return true;
}
public:
memoryGame6() {
// Initialization of array with through constructor
for (int i = 0; i < BoardSize; i++)
for (int j = 0; j < BoardSize; j++)
face[i][j] = '*';
}
// Function to play game
void play() {
shuffle();
while (!win()) {
table();
pick();
}
}
};
int main() {
srand(static_cast<unsigned>(time(nullptr)));
memoryGame6 mg6;
mg6.play();
}
|