I'm still a beginner trying to learn some C++.
I'm trying to pass in a random number to a function to generate a random 2D array for a small game. Unfortunately, it always prints out the same option instead of generating a random one each time.
Could you please help? I'd appreciate it.
Could you please advise me also if there is a better way to randomize 'X' and 'O' within a 2D array than simply hard-coding it as I have tried?
Thank you very much.
#include <iostream>
#include <cstdlib>
using namespace std;
void generateBlock(int n)
{
switch (n)
{
case 0:
{
char blocks1[4][4] = { 'X', 'X', 'O', 'O',
'X', 'X', 'O', 'O',
'O', 'O', 'O', 'O',
'O', 'O', 'O', 'O' };
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
cout << blocks1[i][j];
}
cout << endl;
}
return;
}
case 1:
{
char blocks2[4][4] = { 'X', 'X', 'O', 'O',
'O', 'O', 'X', 'X',
'O', 'O', 'O', 'O',
'O', 'O', 'O', 'O' };
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
cout << blocks2[i][j];
}
cout << endl;
}
return;
}
case 2:
{
char blocks3[4][4] = { 'X', 'X', 'O', 'O',
'X', 'O', 'O', 'O',
'X', 'O', 'O', 'O',
'O', 'O', 'O', 'O' };
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
cout << blocks3[i][j];
}
cout << endl;
}
return;
}
}
}
int main()
{
int n = rand() % 3;
generateBlock(n);
}
Aucun commentaire:
Enregistrer un commentaire