gpt4 book ai didi

c++ - 内存配对游戏如何随机化数组中的字符

转载 作者:行者123 更新时间:2023-11-28 05:28:45 26 4
gpt4 key购买 nike

您好,我对这项作业有疑问。我的程序是 C++ 中的内存匹配游戏,它可以运行,但是每次用户输入有效或无效响应后,我都需要让我的二维数组中的字符移动位置。他们停留在与初始化相同的位置。我尝试了多种想法,但没有得出结论。甚至一些可能有帮助的提示也会受到赞赏。

#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 中随机选择一个项目并将其存储在 vector 中。删除该项目并重复直到列表为空。然后,您在数组中有一个包含“混洗”索引的 vector。不要直接修改数组,而是将索引的 vector 存储到数组中。

参见 std::liststd::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 并从您的卡片组中随机分配一张卡片。

这就是我一开始发布的洗牌想法的用武之地。

关于c++ - 内存配对游戏如何随机化数组中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39989383/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com