本篇文章的目標,在玩家輸入違規時,於畫面上即時給予提示或標記,並額外在遊戲畫面上顯示:
我們需要在玩家輸入數字後,檢查該格是否合法。檢查邏輯包含三個部分:
若違反規則,將該格標記為錯誤狀態,例如:
這樣能讓玩家一眼看出哪裡填錯,並立即修正。
在建立 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://github.com/leetcode-golang-classroom/sudoku-game/actions/runs/17561695048/job/49879373664
今天我們完成了:
明天的重點將會是 遊戲勝利檢查與結束畫面設計: