1

今天我开始编写我的第一个 SFML 程序,它应该是一个 Snake 游戏,一切进展顺利,直到我开始制作二维类数组,它应该保存每个图块的信息。一些奇怪的事情开始发生:程序编译,并在我尝试将数字流式传输到字符串时崩溃,即使在编写数组代码之前该位工作......我也尝试一点一点地注释掉所有内容得到了更奇怪的结果...

#include <SFML/Graphics.hpp>
#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
#include <windows.h>
int main(){
char KeyPressed;
int angle = 0;
float FPS;
sf::Clock Clock;
std::ostringstream oss;
sf::String sFPS;
sf::RenderWindow window(sf::VideoMode(510,510),"Snake Prototype");
window.display();
class Tile {
public:
unsigned int x;
unsigned int y;
unsigned char state;
unsigned char lenght;
sf::RectangleShape make(){
    if(state == 1){
sf::RectangleShape rect(sf::Vector2f(15, 15));
rect.setPosition(x, y);
rect.setFillColor(sf::Color(220, 40, 140));
std::cout<< "Rendering.. State: "<< (int)state<<std::endl; return rect;
}
}
};
    Tile tileArray[30][30];
    int i = 1;
    int t = 1;
while(t <= 30){
while(i <= 30){
        tileArray[i][t].x = i;
        tileArray[i][t].y = t;
        std::cout<<"x:  " << tileArray[i][t].x << "   y:  " << tileArray[i][t].y <<std::endl;
        i++;
}
i = 1;
t++;
}
t = 0;
i = 0;
std::cout<<"LoopOver"<<std::endl;
while(window.isOpen()){
        window.clear(); // If this is commented out the array doesn't initialise correctly, No Idea why
        sf::Event event;
    while(window.pollEvent(event)){
        if(event.type == sf::Event::Closed){window.close();}
        if((event.type == sf::Event::KeyPressed)&&(event.key.code == sf::Keyboard::Escape)){window.close();}
        if((event.type == sf::Event::KeyPressed)&&(event.key.code == sf::Keyboard::Left)){KeyPressed = 4;}
        if((event.type == sf::Event::KeyPressed)&&(event.key.code == sf::Keyboard::Up)){KeyPressed = 1;}
        if((event.type == sf::Event::KeyPressed)&&(event.key.code == sf::Keyboard::Right)){KeyPressed = 2;}
        if((event.type == sf::Event::KeyPressed)&&(event.key.code == sf::Keyboard::Down)){KeyPressed = 3;}
    }
std::cout<<"Polling loop ended"<<std::endl;


//      FPS COUNT
     window.display();
    FPS = 1/Clock.restart().asSeconds();
     std::cout<<"Time gotten"<<std::endl; // random cout's to know, up to which point the program actually runs
     oss<< "Snake Prototype "<<"FPS: "<<(int)FPS;
     std::cout<<"TitleSet"<<std::endl;
    sFPS = oss.str(); // this seems to be the problem, even though it seems like legal c++ code
    std::cout<<"String written"<<std::endl;
    oss.str("");
window.setTitle(sFPS);
std::cout<<"MainLoopover"<<std::endl;
}
return 1;
}

我试图评论那些我认为会导致问题的位,但无论如何,有人能告诉我为什么这个程序会崩溃吗?

4

1 回答 1

1

您的初始化循环从 1 变为 30。这是错误的。如果您将数组索引的大小声明为 30,则数组索引的范围从 0 到 29。程序中发生的所有其他奇怪情况都可能是由于覆盖了与您无关的内存。先解决这个问题。

于 2013-12-28T13:59:56.680 回答