I have this code:
void generar() {
while (true) {
if (yPos == topOfTheWorld) {
scene[xPos][yPos] = 2;
} else if (yPos >= topOfTheWorld) {
scene[xPos][yPos] = 1;
} else if(yPos < topOfTheWorld) {
scene[xPos][yPos] = 0;
} else {
scene[xPos][yPos] = 0;
}
yPos++;
if(yPos>worldHeight) {
topOfTheWorld += 0;
yPos = 0;
xPos++;
}
if (xPos>worldWidth) {
break;
}
}
std::ofstream output("mapa.txt");
for(int y=0;y<worldHeight;y++) {
for(int x=0;x<worldWidth;x++) {
output<<scene[x][y];
if(x<(worldWidth-1)){output<<",";}
}
if(y<(worldHeight-1)){output<<std::endl;}
}
MessageBox(0, "World generation has finished!", "Finished!", MB_OK);
}
That generates a world based in an array. But when I add:
slope = random(5)-2;
To:
if(yPos == worldHeight) {
topOfTheWorld += 0; //There would be the slope var...
if(yPos == worldHeight) {
slope = random(5)-2;
topOfTheWorld += slope;
For some reason the while
becomes an infinite loop, and I don't know why.
(Random Function)
#include <time.h>
#include <windows.h>
int random(int n = 0) {
srand(time(NULL));
if(n!=0){
return rand() % n;
} else {
return rand();
}
}
(Variables)
const int worldWidth = 50;
const int worldHeight = 26;
int topOfTheWorld = worldHeight/2;
int xPos = 0;
int yPos = 0;
int scene[worldWidth][worldHeight];
int slope;
What can I do?
You show that
scene
is defined as:However, your code has this:
Which means you will actually write a value outside the array boundary when
xPos == worldWidth
, and this causes undefined behavior. Adding theslope
variable may cause your variable organization to change in a way that the undefined behavior ends up affecting the values of and or all of your loop control variables.To fix, you should change the erroneous check with:
You have since edited your question with code that makes your
yPos
check incorrect in a similar way.There's a repeated calls to srand in your
random
functionFixes : -