iT邦幫忙

2025 iThome 鐵人賽

DAY 27
2

主題

本篇文章的目標,在玩家輸入違規時,於畫面上即時給予提示或標記,並額外在遊戲畫面上顯示:

  • 剩餘尚未填寫的格數
  • 當前檢測出的錯誤格數

輸入違規的提示設計

我們需要在玩家輸入數字後,檢查該格是否合法。檢查邏輯包含三個部分:

  • 行檢查:確認該數字在該行是否已存在
  • 列檢查:確認該數字在該列是否已存在
  • 宮格檢查:確認該數字在對應的 3x3 宮格內是否已存在

若違反規則,將該格標記為錯誤狀態,例如:

  • 在 UI 上將錯誤格子框線標紅
  • 或是將數字顯示為紅色

這樣能讓玩家一眼看出哪裡填錯,並立即修正。

統計剩餘格數

在建立 Sudoku 遊戲時,已經知道題目設定有值的格子數,就可以算出目標需要填入的格子數目
目標需要填入的格子數目 = 總共格子數 - 題目設定有值的格子數
建立一個累計目前總輸入格子數的變數
透過當下對於輸入狀態的控制(當格子的值從非空到空,則把累積目前總輸入格子數遞減。
當格子的值空到非空,則把累積目前總輸入格子數遞增)
剩餘格數 = 目標需要填入的格子數目 - 累積目前總輸入格子數

統計錯誤格數

與剩餘格數類似,建立一個累計目前總錯誤總數
透過當下對於輸入狀態的控制
當格子數值從格子不合格條件,轉換為合格條件時,則把累計目前總錯誤總數遞增
反之,當格子數值從格子合格條件,轉換為不合格條件時,則把累計目前總錯誤總數遞減

實做邏輯

// handleKeyInput - 處理輸入時
func handleKeyInput(board *game.Board, targetCell *game.Cell, key ebiten.Key,
	targetRow, targetCol int) {
	cellType := targetCell.Type
	// 當格子為題目時
	if cellType == game.Preset {
		return
	}
	value := int(key - ebiten.KeyDigit0)
	// 當輸入格為空格時
	if cellType == game.Empty {
		board.IncreaseFilledCount()
	}
	safed := board.IsSafe(targetRow, targetCol, value)
	if !safed {
		handleConflict(board, cellType, targetRow, targetCol)
	} else {
		handleNonConflict(board, cellType, targetRow, targetCol)
	}
	// 更新輸入
	board.Cells[targetRow][targetCol].Value = value
}

// handleConflict - 處理 Conflict Cell
func handleConflict(board *game.Board, cellType game.CellType,
	targetRow, targetCol int) {
	if cellType != game.InputConflict {
		board.IncreaseConflictCount()
	}
	// 標示為 Conflict Input
	board.Cells[targetRow][targetCol].Type = game.InputConflict
}

// handleNonConflict - 處理 Non-Conflict Cell
func handleNonConflict(board *game.Board, cellType game.CellType,
	targetRow, targetCol int) {
	// 當輸入為 Conflict 時
	if cellType == game.InputConflict {
		board.DescreaseConflictCount()
	}
	// 標示為 Input
	board.Cells[targetRow][targetCol].Type = game.Input
}

畫面上顯示

https://ithelp.ithome.com.tw/upload/images/20250909/20111580xfjqIxTu4a.png

https://ithelp.ithome.com.tw/upload/images/20250909/20111580LTK7MJchqD.png

github action 測試結果

https://github.com/leetcode-golang-classroom/sudoku-game/actions/runs/17561695048/job/49879373664

今日收穫

今天我們完成了:

  • 在輸入違規時,能立即提示玩家(例如紅色數字或框線)
  • 統計並顯示 剩餘格數 與 錯誤格數
  • 建立了遊戲勝負條件的重要基礎

明日預期

明天的重點將會是 遊戲勝利檢查與結束畫面設計:

  • 當剩餘格數為 0 且錯誤格數為 0 → 顯示「恭喜完成!」
  • 設計一個簡單的遊戲結束畫面,並提供重新開始的選項

上一篇
Sudoku 遊戲: 游標控制與玩家輸入
下一篇
Sudoku 遊戲:遊戲勝利檢查與結束畫面設計
系列文
在 ai 時代 gopher 遊戲開發者的 30 天自我養成30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言