您好,我有一个映射类,它正在绘制到屏幕上,但它只在窗口左侧垂直向下绘制。我可以弄清楚我哪里出错了。任何帮助将非常感激。很确定这与我在绘制函数中的 for 循环有关。
void Map::Initialise(const char *filename)
{
std::ifstream openfile(filename);
std::string line;
std::vector <int> tempvector;
while(!openfile.eof())
{
std::getline(openfile, line);
for(int i =0; i < line.length(); i++)
{
if(line[i] != ' ') // if the value is not a space
{
char value[1] = {line[i]}; // store the character into the line variable
tempvector.push_back(atoi(value)); // then push back the value stored in value into the temp vector
}
mapVector.push_back(tempvector); // push back the value of the temp vector into the map vector
tempvector.clear(); // clear the temp vector readt for the next value
}
}
}
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;
sf::Sprite sprite;
for(int i = 0; i < mapVector.size(); i++)
{
for(int j = 0; j < mapVector[i].size(); j++)
{
if(mapVector[i][j] == 0)
rectCol = sf::Color(44, 117, 255);
else if (mapVector[i][j] == 1)
rectCol = sf::Color(255, 100, 17);
rect.SetPosition(j * BLOCKSIZE, i * BLOCKSIZE);
rect.SetColor(rectCol);
Window.Draw(rect);
}
}
}
最佳答案
首先,让你的提取成为while
循环的条件:
while(std::getline(openfile, line))
{
// ...
}
使用openfile.eof()
是一个非常糟糕的主意;仅仅因为您还没有到达文件末尾,并不意味着下一次提取就会成功。你只是继续前进,不知道你是否真的有一个有效的 line
。
其次,这不会正常工作:
char value[1] = {line[i]}; // store the character into the line variable
tempvector.push_back(atoi(value));
我明白您为什么使用 char[1]
- 您希望将其转换为指针,因为 atoi
采用 const char*
。但是,atoi
还期望它指向的数组以 null 终止。你的不是。它只是一个 char
。
有一种更好的方法可以将 char
转换为它所代表的整数。所有数字字符的值保证是连续的:
char value = line[i];
tempvector.push_back(value - '0');
现在,真正的问题来了。仅读取一个字符后,您将 tempvector
插入 mapVector
。您需要将它移出 for
循环之外的行:
while(std::getline(openfile, line))
{
for(int i =0; i < line.length(); i++)
{
// ...
}
// Moved here
mapVector.push_back(tempvector); // push back the value of the temp vector into the map vector
tempvector.clear(); // clear the temp vector readt for the next value
}
关于c++ - 在 C++ 中使用平铺 map 的 SFML 平台游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15796850/