Questa è la classe memory.h:
#include <iostream>
#include <vector>
using namespace std;
class memory
{
public:
memory(int rows0, int cols0);
void gen_matrix();
vector<char> Cards;
vector<bool> Control;
vector<char> Cover;
void UnCover(int pos01, int pos02);
string result;
int Finished();
private:
int rows, cols;
int pos1, pos2;
};
questo il memory.cpp
#include "memory.h"
memory::memory(int rows0, int cols0)
{
cols = cols0;
rows = rows0;
}
void memory::gen_matrix()
{
int size = rows * cols;
Control[size];
char c;
int ind;
string matrix = "\n";
for (int coupple = 0; coupple <2; coupple++)
{
for (int i= 0; i < size/2; i++)
{
c = 'A' + i;
Cards.push_back(c);
Control.push_back(false);
}
}
for (int k = 0; k < Cards.size(); k++) {
int r = k + rand() % (Cards.size() - k); // careful here!
swap(Cards[k], Cards[r]);
}
for (int y = 0; y <rows; y++)
{
for (int x = 0; x < cols; x++)
{
ind = y*cols +x;
matrix += Cards[ind];
Cover.push_back('?');
matrix += "\t";
result += "?";
result += "\t";
} result += "\n";
matrix += "\n";
} cout << result;
cout << matrix;
}
void memory::UnCover(int pos01, int pos02)
{
pos1 = pos01;
pos2 = pos02;
result = "";
//int size = rows * cols;
if (Cards[pos1] == Cards[pos2])
{
Control[pos1] = true;
Control[pos2] = true;
Cover[pos1] = Cards[pos1];
Cover[pos2] = Cards[pos2];
}
/*for (int i= 0; i < size; i++ ){
cout << Cover[i] << "\t";
}*/
int pos;
for (int y = 0; y <rows; y++)
{
for (int x = 0; x < cols; x++)
{
pos = y*cols +x;
result += Cover[pos];
result += "\t";
} result += "\n";
} cout << result;
}
int memory::Finished()
{
int size = rows*cols;
int control;
for (int i = 0; i < size; i++)
{
if(Control[i] == true)
{
control++;
}
}
return control;
}
questo il main:
#include <iostream>
#include <vector>
#include "memory.h"
using namespace std;
int main() {
// insert code here...
int rows, cols;
do {
cout << "\ntype rows: "; cin >> rows;
cout << "type cols: "; cin >> cols;
} while (rows == cols || (rows*cols)%2 !=0);
memory memory(rows, cols);
memory.gen_matrix();
int control;
do {
int pos1, pos2;
cout << "type Card 1: "; cin >> pos1;
cout << "type Card 2: "; cin >> pos2;
memory.UnCover(pos1, pos2);
control = memory.Finished();
if (control == (rows*cols))
{
cout << "YOU WON!";
}
} while (control < (rows*cols));
}
la variabile matrix in memory.cpp mi serviva solo per il controllo di come viene generta la matrice