根據格內數字畫出不同顏色與文字大小
在 2048 遊戲中,棋盤為 4x4 的格子。每個格子可能包含數字(如 2、4、8 ... 2048),需要根據不同數字顯示對應的背景顏色與文字樣式,以提供玩家清晰的視覺提示:
範例對應規則(可擴充):
數字 | 背景色 | 字體大小 | 字體顏色 |
---|---|---|---|
2 | 淺灰色 | 大 | 黑色 |
4 | 米黃色 | 大 | 黑色 |
8 | 橘色 | 中 | 白色 |
16 | 紅色 | 中 | 白色 |
32 | 深紅色 | 中 | 白色 |
64 | 金色 | 中 | 白色 |
128+ | 漸層 / 更深顏色 | 小 | 白色 |
type GameLayout struct {
gameInstance *game.Game
}
// drawCell - 透過目前值來畫出目前 cell 的格子顏色
func (g *GameLayout) drawCell(screen *ebiten.Image, value, row, col int) {
cellXPos := padding + col*(tileSize+padding)
cellYPos := padding + row*(tileSize+padding)
cellColor := getTileColor(value)
cell := ebiten.NewImage(tileSize, tileSize)
cell.Fill(cellColor)
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(float64(cellXPos), float64(cellYPos))
op.ColorScale.ScaleWithColor(g.tileBackgroundColor(value))
screen.DrawImage(cell, op)
}
// drawTileText - 透過目前值來畫出目前 cell 的文字顏色
func (g *GameLayout) drawTileText(screen *ebiten.Image, value, row, col int) {
if value > 0 {
// 繪製數字 (置中)
textValue := fmt.Sprintf("%d", value)
textXPos := (col+1)*padding + col*tileSize + (tileSize)/2
textYPos := (row+1)*padding + row*tileSize + (tileSize)/2
textOpts := &text.DrawOptions{}
textOpts.ColorScale.ScaleWithColor(getTileColor(value))
textOpts.PrimaryAlign = text.AlignCenter
textOpts.SecondaryAlign = text.AlignCenter
textOpts.GeoM.Translate(float64(textXPos), float64(textYPos))
text.Draw(screen, textValue, &text.GoTextFace{
Source: mplusFaceSource,
Size: getFontSize(value),
}, textOpts)
}
}
func (g *GameLayout) Draw(screen *ebiten.Image) {
// 背景色
screen.Fill(color.RGBA{250, 248, 239, 255})
// 畫 4x4 格子
for row := 0; row < gridSize; row++ {
for col := 0; col < gridSize; col++ {
// 取出值
value := g.gameInstance.Data(row, col)
// 畫格子背景
g.drawCell(screen, value, row, col)
// 畫文字
g.drawTileText(screen, value, row, col)
}
}
}
func main() {
ebiten.SetWindowSize(layout.WinWidth, layout.WinHeight)
ebiten.SetWindowTitle("2048 - Day 8 測試")
gameInstance := game.NewGame()
gameInstance.Init([][]int{
{2, 4, 8, 16},
{32, 64, 128, 256},
{512, 1024, 2048, 4096},
{0, 0, 0, 8192},
}, nil, nil)
gameLayout := layout.NameGameLayout(gameInstance)
if err := ebiten.RunGame(gameLayout); err != nil {
log.Fatal(err)
}
}