Hello all, am working on the 'dungeon crawl' problem at present. Am happy with my game grid and at the moment I am trying to place a number of traps 'T' into the array at 'random' locations - the number depending on the level selected.
The code follows - problem is that the cout loops seem to be printing only the 'dots' still. Where have I taken a wrong turn - hints please.
#include <cstdlib>
#include <iostream>
#include <string>
#include <ctime>
#include <limits>
usingnamespace std;
int main ()
{
char grid [10][10]; // basic game grid size
bool grid_check [10][10]; //to flag positions once something is there
int x = 0, y = 0; //x-axis and y-axis position
int randx = 0, randy =0; //random values to be passed to x and y position
int ran1; //temp store for random number
int rn; //variable for number of random numbers required
int level; //place to store level selection
int n;
// Take appropriate level input
while ((cout << string(50, '\n') <<"Please select difficulty level 1-5\n") && (!(cin >> level) || level<1 || level>5))
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
// basing number of random nmbers needed on level
rn = (10*level);
// generating the numbers and putting markers into the check array memory
for (n=0; n==rn; n++)
{
srand((unsigned)time(0));
randx =rand()% 11;
randy =rand()% 11;
grid_check[randx][randy]=1;
}
//fill rest of array up with dots
for (x=0; x<10; x++)
{
for (y=0; y<10; y++)
{
if (grid_check[x][y]!=1)
{
grid[x][y]='.';
}
else
grid [x][y]='T';
}
}
cout << string(50, '\n'); //create space
//print out array
for (x=0; x<10; x++)
{
cout << "\n\t\t\t\t";
for (y=0; y<10; y++)
{
cout << grid[x][y] << " ";
}
}
cout << endl;
return 0;
}
for (n=0; n==rn; n++)
{
srand((unsigned)time(0));
randx =rand()% 11;
randy =rand()% 11;
grid_check[randx][randy]=1;
}
Unless 'rn' is zero, this loop will never execute. And even if it is zero, it will only execute once. You probaly meant n < rn
Also... do not srand before every call to rand. You only srand once, at program startup. Calling srand multiple times like this will destroy the RNG. This is a very common mistake.
Many thanks for the advice, exactly what i needed!
The repeated call to srand was really making things go tits up - keep forgetting that it's based on clock time and only needs initialising once - should have remembered from my last dealings with it in the noughts & crosses game.
As for the
n==rn;
error, - I keep verbalising those for loops as: "variable starts as; do until; what happens after each itteration" when it should be along the lines of "variable starts as; do while; what happens after each itteration".
I guess things stay in memory with more practice and patience - at least i hope!
I'll post back when the next stumbling block is reached - thanks again,