如何解决循环结束时崩溃的控制台应用程序寻求建议 关闭图片
|解决方法
这里的问题是您要定义drawEngine的宽度和高度为80:
class DrawEngine
{
public:
DrawEngine (int xSize = 80,int ySize = 50);
...
};
但是,创建关卡时,您的意思是关卡的尺寸应为30x30:
bool Game::run(void)
{
level = new Level(&drawArea,30,30);
....
}
然后将级别设置为具有30x30大小的数组,并将该30x30数组传递给drawArea:
Level::Level(DrawEngine *de,int w,int h)
{
drawArea = de;
width = w;
height = h;
player = 0;
// char** create memory for every position in the level.
level = new char *[width];
for (int x = 0; x < width; x++)
level[x] = new char[height];
//create the level
createLevel();
drawArea->setMap(level);
}
实际上,这里的循环超出了范围,因为它认为它具有可以在尺寸仅为80x80的尺寸上循环的数组,而实际上只有30x30的尺寸:
void DrawEngine::drawBackground(void)
{
if (map)
{
for (int y = 0; y < screenHeight; y++)
{
gotoxy(0,y);
for (int x = 0; x < screenWidth; x++)
cout << tileImage[map[x][y]];
}
}
}
那么您如何解决呢?好吧,您必须更改大小以使它们以某种方式匹配,或者您添加代码以正确考虑屏幕可能大于实际水平的事实。
例如,您可能想要按照以下方式进行操作:
for (int x = 0; x < levelWidth; x++)
{
for (int y = 0; y < levelHeight; y++)
{
// do stuff with level[x][y]
}
}
相对于:
for (int x = 0; x < screenWidth; x++)
{
for (int y = 0; y < screenHeight; y++)
{
// do stuff with level[x][y]
}
}
因为在第二种情况下
if (screenWidth > levelWidth || screenHeight > levelHeight)
BadThingsWillHappen();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。