2

我有这个代码:

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);

}

这会生成一个基于数组的世界。但是当我添加:

slope = random(5)-2;

至:

if(yPos == worldHeight) {
    topOfTheWorld += 0; //There would be the slope var...

if(yPos == worldHeight) {
    slope = random(5)-2;
    topOfTheWorld += slope;

由于某种原因,它while变成了一个无限循环,我不知道为什么。

(随机函数)

#include <time.h>
#include <windows.h>

int random(int n = 0) {

srand(time(NULL));

if(n!=0){
return rand() % n;
} else {
return rand();
}

}

(变量)

const int worldWidth = 50;
const int worldHeight = 26;
int topOfTheWorld = worldHeight/2;
int xPos = 0;
int yPos = 0;
int scene[worldWidth][worldHeight];
int slope;

我能做些什么?

4

2 回答 2

2

您表明scene定义为:

int scene[worldWidth][worldHeight];

但是,您的代码具有以下内容:

        if (xPos>worldWidth) {
                    break;
        }

这意味着您实际上会在 时在数组边界之外写入一个值xPos == worldWidth,这会导致未定义的行为。添加slope变量可能会导致您的变量组织发生变化,未定义的行为最终会影响您的循环控制变量的值和/或所有循环控制变量。

要修复,您应该使用以下命令更改错误检查:

        if (xPos>=worldWidth) {
                    break;
        }

yPos此后,您使用代码编辑了您的问题,以类似的方式使您的检查不正确。

于 2013-09-21T16:59:14.707 回答
1

在您的random函数中重复调用 srand

修复: -

void generar() {

srand(time(NULL)); //Remove srand() from random(), add it here
bool finished = false;

    while (!finished) {
        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) {
           // slope = random(5)-2; your random call
            topOfTheWorld += 0;
            yPos = 0;
            xPos++;
        }

        if (xPos>worldWidth) {
            finished = true;
           //goto Guardar; not required, 
          //also use of goto is bad programming practice
        }
    }
于 2013-09-21T16:45:31.463 回答