教程 8:存檔
用 game/save 的帶版本存檔槽,跨啟動儲存玩家的最高分和玩過的局數,並在標題介面和結束介面顯示最高分。
完成後的程式碼在 examples/tutorial/ch08-save。
要儲存什麼
記錄是 records.go 裡一個帶 JSON 標籤的小結構體:
type records struct {
Best int `json:"best"`
Games int `json:"games"`
}
func (r *records) add(score int) (best bool) {
r.Games++
if score > r.Best {
r.Best = score
return true
}
return false
}
存檔倉庫
save.NewStorageStore 把存檔槽儲存在應用的 core.Storage 裡,所有目標平臺都有它,包括 Web:
const (
savePrefix = "starcatcher"
recordsSlot = "records"
recordsVersion = 1
)
func newRecordsStore(store core.Storage) *save.Store {
return save.NewStorageStore(store, savePrefix, save.WithVersion(recordsVersion))
}
Save 把存檔槽寫成帶版本信封的 JSON,即 {"version":1,"data":{"best":12,"games":5}},儲存在鍵 starcatcher.slot.records 下,並把上一份完好的副本留作備份;最新副本損壞時,Load 會退回到備份。以後的版本里 records 改變結構時,提高 recordsVersion,並給倉庫加一個從舊版本升級的 save.WithMigration;之後 Load 會在讀取時升級舊存檔。資料遷移和基於檔案的倉庫見 save 指南。
啟動時載入,結束時儲存
載入只在遊戲啟動時進行一次:
func loadRecords(st *save.Store) (r records, newer bool) {
if err := st.Load(recordsSlot, &r); err != nil {
return records{}, errors.Is(err, save.ErrFutureVersion)
}
return r, false
}
第一次啟動時 Load 返回 save.ErrNotFound,遊戲從空記錄開始。連備份都讀不出來的存檔槽同樣從頭開始,而不是把玩家擋在遊戲外面,下一次儲存會替換它。由更新版本的遊戲寫入的存檔槽則不同:這個版本讀不懂它,但裡面存著玩家的記錄,比如執行過新版本之後,瀏覽器裡還快取著舊的網頁包。遊戲不帶記錄地執行,loadRecords 報告 newer,遊戲把它儲存在 keepSlot 裡。
一局結束時,遊戲記下這一局並儲存:
func (s *starCatcher) finish() {
s.newBest.Set(s.records.add(s.world.score))
s.best.Set(s.records.Best)
if !s.keepSlot {
_ = s.store.Save(recordsSlot, s.records)
}
s.setPhase(phaseOver)
}
Save 只會在儲存已滿時失敗,這時丟失的也只是這一局的記錄。只要設定了 keepSlot,遊戲就完全不儲存,新版本回來時看到的記錄和它離開時一樣。
顯示最高分
有了最高分之後,標題介面會顯示它;玩家打破紀錄時,結束介面顯示“New best!”:
core.Show{
When: s.newBest.Get,
Then: func(*core.Scope) core.Node {
return core.Text{TestID: "new-best", Content: "New best!", Style: core.Style{Color: bestColor, FontSize: 16, FontWeight: core.FontWeightBold}}
},
Else: func(*core.Scope) core.Node { return s.bestLine() },
},
執行這一章,玩一局,關掉應用再開啟:標題介面會顯示你的最高分。
測試存檔
nsgotest 給每個應用一份獨立的儲存,除非測試用 nsgotest.Storage 填充,否則是空的;app.Storage() 讓測試讀取遊戲寫入的內容。測試在兩個倉庫之間儲存和載入記錄,檢查儲存裡的信封是否完全符合預期,並檢查損壞的存檔槽和來自未來版本的存檔槽都會從頭開始,而且只有後者被報告為 newer:
func TestUnreadableRecordsStartAfresh(t *testing.T) {
for _, tc := range []struct {
name, raw string
newer bool
}{
{"corrupt", "{not json", false},
{"future", `{"version":99,"data":{"best":5,"games":1}}`, true},
} {
t.Run(tc.name, func(t *testing.T) {
app := nsgotest.Start(t, empty, nsgotest.Storage(map[string]string{recordsKey: tc.raw}))
got, newer := loadRecords(newRecordsStore(app.Storage()))
if got != (records{}) || newer != tc.newer {
t.Fatalf("records = %+v, newer %v; want none, newer %v", got, newer, tc.newer)
}
})
}
}
應用測試玩兩局,檢查第一局是新紀錄、分數更低的第二局不是;啟動一個儲存裡已有最高分 12 的應用,檢查標題介面顯示了它;再在一個來自未來版本的存檔槽上玩一局,檢查這個存檔槽沒有被改動。
下一章
遊戲已經完整了。第 9 章讓它準備好交到玩家手裡。