我正在玩一个RTS游戏,我正在用这种方式从txt文件加载单位:
1 1 700 200 10
/ unit type / / player / / x co-ord / / y co-ord / / health /
我正在使用定居者的矢量(我目前只有单位)OBJECTS(不是指针)来保留所有单位
当我加载单位并尝试在屏幕上绘制它们时,它们就不存在了。我做了一些测试,发现即使我从txt文件加载后,矢量“定居者”也是空的
main.cpp的代码:
vector<Settler> settlers;
...
void load_units(string filename)
{
settlers.clear();
ifstream unit_file(filename.c_str());
string line;
vector<vector<int> > ww;
while(unit_file.eof())
{
while(getline(unit_file, line))
{
stringstream ss(line);
int i;
vector<int> w;
while( ss >> i )
{
w.push_back(i);
}
ww.push_back(w);
}
}
for(int i = 0; i < ww.size(); i++)
{
int type = ww[i][0];
int player = ww[i][1];
int x = ww[i][2];
int y = ww[i][3];
int hp = ww[i][4];
if(type == 1)//settler
{
Settler settler(x, y, hp, player);
settlers.push_back(settler);
}
}
unit_file.close();}
...
void init() {
SDL_Init( SDL_INIT_EVERYTHING );
TTF_Init();
Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 );
SDL_WM_SetIcon(IMG_Load("icon.png"), NULL);
screen = SDL_SetVideoMode(1600, 900, 32, SDL_FULLSCREEN);
map = IMG_Load("tlo.png");
bar = IMG_Load("bar.png");
pause_menu = IMG_Load("menu.png");
save_game_menu = IMG_Load("save_game_menu.png");
save_prompt = IMG_Load("saved_prompt.png");
load_game_menu = IMG_Load("load_game_menu.png");
load_prompt = IMG_Load("loaded_prompt.png");
intro_control = true;
menu = true;
running = false;
paused = false;
saving = false;
loading = false;
mapX = 0;
mapY = 0;
Xoffset = 0;
Yoffset = 0;
load_map("mapa1.txt");
load_units("units1.txt");
for(int i = 0; i < 60; i++)
{
string file_frame;
stringstream ss;
ss << i + 1;
if(i < 9)
{
file_frame = ("intro/000");
}else
{
file_frame = ("intro/00");
}
file_frame.append(ss.str());
file_frame.append(".png");
intro[i] = IMG_Load(file_frame.c_str());
}}
...
int main( int argc, char* args[] ) {
int frame = 0;
Timer fps;
init();
Player p1(0, player_1_colour, "player 1");
int frame_control = 0;
while(intro_control)
{
.....
PS:我怀疑“while(unit_file.eof()){”语句可能存在错误。但这只是猜测
答案 0 :(得分:1)
您的代码存在一些问题:
我认为以下内容可以更好地解决您的问题:
首先,定居者结构:
struct Settler {
int type; // Maybe some of those should be unsigned,
// but I just left them as you already had them
int player;
int x;
int y;
int health;
};
然后你可以重载&gt;&gt;您的类的运算符,允许从任何输入流中流式传输它。它将流作为第一个参数读取,将结果作为第二个参数读取的对象:
std::istream& operator>>(std::istream in&, Settler& settler) {
// Just read the values in the corresponding fields of Settler
return in >> settler.type
>> settler.player
>> settler.x
>> settler.y
>> settler.health;
}
然后你可以使用简单的while循环读取整个定居者文件:
int main() {
std::ifstream file("test.txt");
Settler current;
std::vector<Settler> settlers;
while(file >> current) { // Read as long as it's possible to
// read a Settler
settlers.push_back(current);
};
}
有一个工作示例(也可以重载&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; }