iT邦幫忙

2025 iThome 鐵人賽

DAY 20
2

主題

在前面我們已經完成了格子繪製、旗子標記與遊戲狀態判斷。今天要來加上 遊戲計時器 的 UI 顯示。這個功能是經典踩地雷遊戲中不可或缺的要素,能讓玩家隨時掌握遊戲進度。

🎯 今日重點

  • 新增遊戲開始後的計時器(秒數)
  • 在畫面頂端 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

我們把 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)
}

✅ 驗收條件

  • 開始遊戲後,計時器從 0 開始,並持續增加。
  • 遊戲結束(踩雷或勝利)後,計時器停止。

執行結果

https://ithelp.ithome.com.tw/upload/images/20250901/20111580yhOpN1pKda.png

github action 執行結果

https://github.com/leetcode-golang-classroom/mine-sweeper-game/actions/runs/17360702849

🏁 今日收穫

  • 學會了如何用 time.Since() 來實作遊戲計時器。
  • 完成經典踩地雷遊戲中不可或缺的計時 UI。

🔮 明日預告

明天將會來實做選擇難度的 ui


上一篇
踩地雷遊戲:重新開始功能與 UI 按鈕互動
系列文
在 ai 時代 gopher 遊戲開發者的 30 天自我養成20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言