gpt4 book ai didi

c++ - 使用 C++ 的 SFML 平台游戏

转载 作者:太空宇宙 更新时间:2023-11-04 11:57:05 26 4
gpt4 key购买 nike

嘿,我目前正在制作一个 sfml 平台游戏并打算使用 map 图 block ,但是在实现我的 map 类之后,它出现了一个未处理的异常。我先调用初始化函数,然后在最后调用 drawmap。这是代码..

    void Map::Initialise(const char *filename)
{
std::ifstream openfile(filename);
if(openfile.is_open())
{
std::string tempLine;
std::getline(openfile, tempLine);

tempLine.erase(std::remove (tempLine.begin(), tempLine.end(), ' '), tempLine.end());
MapX = tempLine.length();

openfile.seekg(0, std::ios::beg);

while(!openfile.eof())
{

openfile >> MapFile[loadCountX][loadCountY];
loadCountX++;
if(loadCountX >= MapX)
{
loadCountX = 0;
loadCountY++;
}
}
MapY = loadCountY;
}

}

void Map::DrawMap(sf::RenderWindow &Window)
{
sf::Shape rect = sf::Shape::Rectangle(0, 0, BLOCKSIZE, BLOCKSIZE, sf::Color(255, 255, 255, 255));
sf::Color rectCol;
for(int i = 0; i < MapX; i++)
{
for(int j = 0; j < MapY; j++)
{
if(MapFile[i][j] == 0)
rectCol = sf::Color(44, 117, 255);
else if (MapFile[i][j] == 1)
rectCol = sf::Color(255, 100, 17);

rect.SetPosition(i * BLOCKSIZE, j * BLOCKSIZE);
rect.SetColor(rectCol);
Window.Draw(rect);
}
}

最佳答案

你的文件循环很糟糕,使用 eof 循环会导致未定义的行为,通常是一种糟糕的文件循环方法。而是遵循这种结构的循环:

fileIn >> data
//while fileIn object is good
while(fileIn) {
//handle data variable
fileIn >> data; //re-read data in
}

您想在读入下一个变量之前操纵和处理您的数据,您做的恰恰相反。因此,您的文件到达 eof,但您最后一次尝试读取数据并处理它,这会引发异常。

扩展我上面所说的:

openfile >> MapFile[loadCountX][loadCountY];

//while your input stream is still good
while(openfile)
{
//handle your file data
loadCountX++;
if(loadCountX >= MapX)
{
loadCountX = 0;
loadCountY++;
}
//now read in again AFTER
openfile >> MapFile[loadCountX][loadCountY];
}

应正确读入和存储数据。

关于c++ - 使用 C++ 的 SFML 平台游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15773870/

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