當盤面已無空格且無法合併,判定遊戲結束。
這是 2048 遊戲的重要終止條件,能讓玩家在無法再進行任何動作時,看到明確的「Game Over」提示。
// hasEmptyTile - 判斷是否還有可移動的位置
func (g *Game) hasEmptyTile() bool {
for row := 0; row < sideSize; row++ {
for col := 0; col < sideSize; col++ {
if g.board[row][col] == 0 {
return true
}
}
}
return false
}
// canMerge 判斷是否有可以合併的 tiles
func (g *Game) canMerge() bool {
for row := 0; row < sideSize; row++ {
for col := 0; col < sideSize; col++ {
if col < sideSize-1 && g.board[row][col] == g.board[row][col+1] {
return true
}
if row < sideSize-1 && g.board[row][col] == g.board[row+1][col] {
return true
}
}
}
return false
}
// IsGameOver - 判斷遊戲是否無法繼續
func (g *Game) IsGameOver() bool {
return !g.hasEmptyTile() && !g.canMerge()
}
func (g *GameLayout) Draw(screen *ebiten.Image) {
// 背景色
screen.Fill(color.RGBA{250, 248, 239, 255})
// 畫出目前局面
g.drawBoard(screen)
// 當 gameOver 顯示 GameOver
if g.isGameOver {
g.drawGameOver(screen)
}
}
由於版面不足,所以其他相關的繪圖邏輯可以在 github 上作搜尋查看
// Update - 用來處理畫面偵測,與使用者互動,並且觸發狀態變更
func (g *GameLayout) Update() error {
// 判斷是否遊戲結束
if g.isGameOver {
// 處理 restart 邏輯
g.handleRestartGame()
return nil
}
// 根據輸入產生對應的更新
g.handleInput()
// 根據目前的盤面跟更新是否能夠繼續執行
if g.gameInstance.IsGameOver() {
g.isGameOver = true
}
return nil
}
處理 restart 的判定如下
// handleRestartGame - 偵測目前 restart button
func (g *GameLayout) handleRestartGame() {
if ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) {
x, y := ebiten.CursorPosition()
if restartButtonRect.Min.X <= x && x <= restartButtonRect.Max.X &&
restartButtonRect.Min.Y <= y && y <= restartButtonRect.Max.Y {
g.restartGame()
}
}
}
// restartGame - 重設目前遊戲狀態
func (g *GameLayout) restartGame() {
g.gameInstance.InitGame()
g.isGameOver = false
}
https://github.com/leetcode-golang-classroom/2048-game/actions/runs/17177641085/job/48735744708
Day 11 — You Win 的顯示勝利條件