您好,我在此作业方面遇到问题。我的程序是C ++中的Memory Match游戏,它可以运行,但是每次用户输入有效或无效的响应后,我都需要获取2D数组中的字符以移动位置。他们停留在与初始化相同的位置。我尝试了多种想法,但没有得出任何结论。甚至可能会有所帮助的一些提示也将受到赞赏。
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<string>
using namespace std;
class Game //Memory Match Game
{
private:
char cards[4][4] = { { '@', '#', '$', '%' },
{'^', '&', '*', '+'},
{'@', '#', '$', '%'},
{'^', '&', '*', '+' } };
char deck[16] = { '@','#', '$', '%', '^','&', '*', '+' }; //not being used atm
int r1, r2, c1, c2;
public:
Game()
{
r1 = 0; r2 = 0; c1 = 0; c2 = 0;
}
void begin()
{
srand((unsigned)time(NULL));
for (int x = 0; x < 4; x++) //begin designating cards
{
for (int y = 0; y < 4; y++)
{
cards[rand() % x][rand() % y]; // <:::::[:::] FIX
cout << " " << cards[x][y] << " ";
}
cout << endl;
}
cout << " \n 1 2 3 4\t\n";
cout << " ";
for (int x = 0; x <= 8; x++)
{
cout << "_";
}
cout << endl;
for (int x = 0; x < 4; x++) //appropriate positioning
{
cout << x + 1 << " | ";
for (int y = 0; y < 4; y++)
{
cout << "? ";
}
cout << endl;
}
cout << endl;
input();
}
void input()
{
srand(time(0));
cout << "Please type in the row and column of choice.\n"; //begin user play
cin >> r1;
cin >> c1;
cout << "Please type in the row and column of choice\n";
cin >> r2;
cin >> c2;
r1--; r2--; c1--; c2--;
cout << " 1 2 3 4\n";
cout << " ";
for (int x = 0; x <= 8; x++)
{
cout << "_";
}
cout << endl;
for (int x = 0; x < 4; x++)
{
cout << x + 1 << " | ";
for (int y = 0; y < 4; y++)
{
if ((x == r1) && (y == c1))
{
cout << cards[x][y] << " ";
}
else if ((x == r2) && (y == c2))
{
cout << cards[x][y] << " ";
}
else cout << "? ";
}
cout << endl;
}
match();
}
void match()
{
if (cards[r1][c1] == cards[r2][c2])
{
cout << "Valid Match!\n";
input();
}
else
cout << "Invalid Match!\n";
input();
}
};
int main()
{
Game memoryMatch;
memoryMatch.begin();
system("pause");
}
一种“洗牌”卡的方法是在其中创建一个list
包含数组所有索引的。从中随机选择一个项目list
并将其存储在中vector
。删除该项目并重复直到列表为空。然后,您vector
在阵列中有了一个“随机”索引。不要直接修改数组,而是将vector
索引a存储到数组中。
请参阅std::list
和std::vector
,以及擦除方法。
https://www.sgi.com/tech/stl/List.html
https://www.sgi.com/tech/stl/Vector.html
根据下面的评论,我为您提供了另一种选择,但没有解释您的代码为何无法正常工作。对此,有几个原因。
void begin()
{
srand((unsigned)time(NULL));
for (int x = 0; x < 4; x++) //begin designating cards
{
for (int y = 0; y < 4; y++)
{
cards[rand() % x][rand() % y]; // <:::::[:::] FIX
cout << " " << cards[x][y] << " ";
}
cout << endl;
}
这不起作用的主要原因是因为您要分配给数组中的随机x和y元素。您可以分配一个插槽一次,多次或根本不分配。您需要做的是为数组中的每个元素分配一个随机项。
像这样的东西会更接近您想要的:
char shuffled_cards[4][4];
for (int y = 0 ; y < 4 ; ++y) {
for (int x = 0 ; x < 4 ; ++x) {
shuffled_cards[y][x] = cards[rand()%4][rand()%4];
}
}
要掌握的主要内容是,您应该处理另一组卡,在这种情况下shuffled_cards
,应从您的一组卡中为它们分配一张随机的卡。
这就是我最初发布的改组想法的来源。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句