使用c ++的SFML平台游戏

时间:2013-04-02 20:36:18

标签: c++ sfml

嘿我正在制作一个sfml平台游戏并开始使用地图图块然而在实现我的地图类后,它会出现一个未处理的异常。 我首先调用初始化函数,然后在最后调用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);
        }
    }

1 个答案:

答案 0 :(得分:1)

您的文件循环不好,使用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];
        }

应正确读入并存储数据。