教程 6:介面
給遊戲加上標題介面、暫停選單和結束介面。它們是畫布上方的原生 NSGo 檢視,按階段顯示,裡面是真正的按鈕,螢幕閱讀器、鍵盤和遊戲測試都能按下它們。
完成後的程式碼在 examples/tutorial/ch06-screens。檢視移到了單獨的檔案 screens.go。
階段
遊戲總是處於四個階段之一,階段儲存在訊號裡,檢視隨之變化:
type phase uint8
const (
phaseTitle phase = iota
phasePlaying
phasePaused
phaseOver
)
所有階段切換都經過同一個方法:
func (s *starCatcher) setPhase(p phase) {
s.phase.Set(p)
s.loop.SetPaused(p == phasePaused)
s.actions.Reset()
}
Loop.SetPaused在暫停時停止迴圈的更新,恢復時不補回離開的時間,所以玩家回來時不會有東西突然跳動。Actions.Reset丟棄按住的觸控和鎖存的按下,所以點在選單按鈕上的那一下不會同時移動籃子。
其餘的切換都很短:
func (s *starCatcher) start() {
s.world.reset()
s.sync()
s.setPhase(phasePlaying)
}
func (s *starCatcher) togglePause() {
switch s.phase.GetUntracked() {
case phasePlaying:
s.setPhase(phasePaused)
case phasePaused:
s.setPhase(phasePlaying)
}
}
GetUntracked 讀取訊號而不讓讀取者訂閱它,這正是按鍵和按鈕處理函式需要的。
世界現在只在遊戲進行時推進,一局結束時切換到 phaseOver:
func (s *starCatcher) update(dt time.Duration) {
s.actions.Step()
if s.phase.GetUntracked() != phasePlaying {
return
}
// Read the moves and step the world as before…
if s.world.over {
s.setPhase(phaseOver)
}
}
每個階段一個介面
view 把各個介面放在場地上方,每個介面只在它的階段才構建:
return core.View{
Style: core.Style{FlexGrow: 1, FlexShrink: 1, Background: barColor},
Children: []core.Node{
field,
s.when(phasePlaying, s.hud),
s.when(phaseTitle, s.title),
s.when(phasePaused, s.paused),
s.when(phaseOver, s.gameOver),
},
}
func (s *starCatcher) when(p phase, screen func() core.Node) core.Node {
return core.Show{
When: func() bool { return s.phase.Get() == p },
Then: func(*core.Scope) core.Node { return screen() },
}
}
每個選單都是一個居中的面板,裡面有標題和按鈕:
func (s *starCatcher) paused() core.Node {
return panel("paused",
heading("Paused"),
button("Resume", s.togglePause),
button("Quit", s.quit),
)
}
button 是一個帶標籤、內含文字的 base.Button。因為選單是原生檢視而不是畫在畫布裡的圖,它們自然得到平臺的文字渲染和無障礙支援:螢幕閱讀器會讀出“Resume,按鈕”,Tab 在按鈕之間移動,Return 或 Space 按下獲得焦點的按鈕。HUD 保留 PointerEventsBoxNone,所以落在分數、暫停按鈕和生命之間的觸控仍會到達場地。
按鍵
Enter 在標題介面或一局結束後開始遊戲,Escape 或 P 暫停和繼續:
cx.OnKey("enter", func() {
if p := s.phase.GetUntracked(); p == phaseTitle || p == phaseOver {
s.start()
}
})
for _, key := range []string{"escape", "p"} {
cx.OnKey(key, s.togglePause)
}
執行這一章。它從標題介面開始;Start 開始一局,Pause 或 Escape 讓它停下,一局結束時會告訴你接住了多少顆星星。
測試介面
測試按角色和標籤按下按鈕,就像使用者找到它們一樣:
func TestPauseStopsTheWorld(t *testing.T) {
app, s := startPlaying(t)
s.world.spawnIn = time.Hour
s.world.drop(kindStar, 0, 40)
app.Advance(step)
app.Press("role:button Pause")
app.Find("text:Paused")
y := s.world.items[0].y
app.Advance(time.Second)
if got := s.world.items[0].y; got != y {
t.Fatalf("star fell from %v to %v while paused", y, got)
}
app.Press("role:button Resume")
app.Advance(time.Second / 2)
if got := s.world.items[0].y; got <= y {
t.Fatalf("star at %v after resuming, want below %v", got, y)
}
}
其他測試檢查:標題介面上沒有東西落下;Escape 和 P 切換暫停;一局結束時提供 Play again;Quit 回到標題介面且場地是空的。第 5 章的規則測試原樣保留,因為世界沒有變。
下一章
遊戲還沒有聲音。第 7 章給它加上聲音。