在前面我們已經完成了格子繪製、旗子標記與遊戲狀態判斷。今天要來加上 遊戲計時器 的 UI 顯示。這個功能是經典踩地雷遊戲中不可或缺的要素,能讓玩家隨時掌握遊戲進度。
1 在 Game 結構加入開始時間
// Game - 遊戲物件
type Game struct {
Board *Board // 棋盤物件
IsGameOver bool // 是否遊戲結束
IsPlayerWin bool // 玩家是否獲勝
startTime time.Time // 遊戲開始時間
}
2 在 GameLayout 加入經過時間用來顯示
// 遊戲畫面狀態
type GameLayout struct {
gameInstance *game.Game // 遊戲物件
ClickCoord *Coord // 使用者點擊座標
elapsedTime int // 經過時間
}
如果遊戲還在進行就持續更新經過時間
// 當遊戲還沒停止時,就更新經過時間
if !g.gameInstance.IsGameOver && !g.gameInstance.IsPlayerWin {
g.elapsedTime = g.gameInstance.GetElapsedTime()
}
// GetElapsedTime - 取出從 startTime 之後到目前為止的時間
func (g *Game) GetElapsedTime() int {
return int(time.Since(g.startTime).Seconds())
}
我們把 UI 畫在上方黃色區域,顯示「計時器」。
// drawElaspedTimeInfo
func (g *GameLayout) drawElaspedTimeInfo(screen *ebiten.Image) {
// 畫旗子面板(固定在左方)
textValue := fmt.Sprintf("%03d", g.elapsedTime)
textXPos := ScreenWidth - gridSize/2 + len(textValue)
textYPos := PaddingY
textOpts := &text.DrawOptions{}
textOpts.ColorScale.ScaleWithColor(getTileColor(-1))
textOpts.PrimaryAlign = text.AlignEnd
textOpts.SecondaryAlign = text.AlignCenter
textOpts.GeoM.Translate(float64(textXPos), float64(textYPos))
text.Draw(screen, textValue, &text.GoTextFace{
Source: mplusFaceSource,
Size: 20,
}, textOpts)
emojiValue := "⏰"
emojiXPos := ScreenWidth - 3*gridSize + len(emojiValue)
emojiYPos := PaddingY
emojiOpts := &text.DrawOptions{}
emojiOpts.ColorScale.ScaleWithColor(getTileColor(IsClock))
emojiOpts.PrimaryAlign = text.AlignStart
emojiOpts.SecondaryAlign = text.AlignCenter
emojiOpts.GeoM.Translate(float64(emojiXPos), float64(emojiYPos))
text.Draw(screen, emojiValue, &text.GoTextFace{
Source: emojiFaceSource,
Size: 30,
}, emojiOpts)
}
https://github.com/leetcode-golang-classroom/mine-sweeper-game/actions/runs/17360702849
明天將會來實做選擇難度的 ui