2017-07-05 76 views
0

我有以下結構:如何在結構中保存ncurses窗口?

typedef struct gameState { 
    WINDOW *game; 
    character *player; 
    finalPosition positions[5]; 
    int level, found, timeSpent[3]; 
} gameState; 

我如何能在gameState.game節省ncurses的窗口?

這就是我創建窗口的方式。

WINDOW * game = newwin(20, 50, 2, 2); 

我覺得我的問題很可能是一個指針的問題,我想一個指針保存到一個結構,每當我離開那個創造了這個指針的函數,它刪除其內容的指針指向。

我的最終目標是將整個結構保存到二進制文件中。我知道ncurses具有putwin()函數,它將窗口保存到二進制文件中,但是我需要將窗口和此結構的其餘內容保存在同一個二進制文件中,所以putwin()不能解決我的問題。

+0

你的結構需要,如果你把它初始化爲動態分配你的功能。然後將其'game'變量分配爲'gameState-> game = newwin(20,50,2,2)'或'gameState-> game = game'。 –

+1

看起來像XY-問題。你爲什麼要保存窗口?這是一個前端。要保存遊戲狀態,您需要保存後端。 –

+0

@EugeneSh。,我會這樣做,謝謝你的建議。 –

回答

0

雖然很有可能您將序列化產生窗口的遊戲狀態而不是窗口本身,但使用putwingetwin來串行化並檢索ncurses窗口沒有任何問題。

putwin只是將窗口的描述寫入給定的FILE。它不倒帶文件流,也不需要倒帶。它也不關閉文件流。同樣,getwin只讀取從當前讀取點開始的給定FILE的窗口描述。

所以,你可以使用putwin/getwin的序列化過程的一部分:

int serialiseWindow(Window* game, FILE* file) { 
    return putwin(game, file); 
} 

int serialiseGameState(gameState *state, FILE* file) { 
    int status; 
    status = serialiseWindow(state->game, file); 
    if (status != OK) return status; 
    status = serialisePositionArray(state->positions, 
            (sizeof state->positions)/(sizeof *state->positions), 
            file); 
    if (status != OK) return status; 
    status = serialiseInteger(state->level, file); 
    if (status != OK) return status; 
    status = serialiseInteger(state->found, file); 
    if (status != OK) return status; 
    status = serialiseIntegerArray(state->timeSpent, 
           (sizeof state->timeSpent)/(sizeof *state->timeSpent), 
           file); 
    return status; 
} 

而且,把它找回來:

int retrieveWindow(Window** game, FILE* file) { 
    Window* win = getwin(file); 
    *game = win; 
    return win ? OK : ERR; 
} 

int retrieveGameState(gameState *state, FILE* file) { 
    int status; 
    status = retrieveWindow(&state->game, file); 
    if (status != OK) return status; 
    status = retrievePositionArray(state->positions, 
           (sizeof state->positions)/(sizeof *state->positions), 
           file); 
    if (status != OK) return status; 
    status = retrieveInteger(&state->level, file); 
    if (status != OK) return status; 
    status = retrieveInteger(&state->found, file); 
    if (status != OK) return status; 
    status = retrieveIntegerArray(state->timeSpent, 
           (sizeof state->timeSpent)/(sizeof *state->timeSpent), 
           file); 
    return status; 
}