11package layout
22
33import (
4+ "fmt"
45 "image/color"
56
67 "github.com/hajimehoshi/ebiten/v2"
8+ "github.com/hajimehoshi/ebiten/v2/text/v2"
9+ "github.com/leetcode-golang-classroom/2048-game/internal/game"
710)
811
912const (
@@ -14,21 +17,54 @@ const (
1417 WinHeight = tileSize * gridSize + padding * (gridSize + 1 )
1518)
1619
17- type GameLayout struct {}
20+ type GameLayout struct {
21+ gameInstance * game.Game
22+ }
23+
24+ // drawCell - 透過目前值來畫出目前 cell 的格子顏色
25+ func (g * GameLayout ) drawCell (screen * ebiten.Image , value , row , col int ) {
26+ cellXPos := padding + col * (tileSize + padding )
27+ cellYPos := padding + row * (tileSize + padding )
28+ cellColor := getTileColor (value )
29+ cell := ebiten .NewImage (tileSize , tileSize )
30+ cell .Fill (cellColor )
31+ op := & ebiten.DrawImageOptions {}
32+ op .GeoM .Translate (float64 (cellXPos ), float64 (cellYPos ))
33+ op .ColorScale .ScaleWithColor (g .tileBackgroundColor (value ))
34+ screen .DrawImage (cell , op )
35+ }
36+
37+ // drawTileText - 透過目前值來畫出目前 cell 的文字顏色
38+ func (g * GameLayout ) drawTileText (screen * ebiten.Image , value , row , col int ) {
39+ if value > 0 {
40+ // 繪製數字 (置中)
41+ textValue := fmt .Sprintf ("%d" , value )
42+ textXPos := (col + 1 )* padding + col * tileSize + (tileSize )/ 2
43+ textYPos := (row + 1 )* padding + row * tileSize + (tileSize )/ 2
44+ textOpts := & text.DrawOptions {}
45+ textOpts .ColorScale .ScaleWithColor (getTileColor (value ))
46+ textOpts .PrimaryAlign = text .AlignCenter
47+ textOpts .SecondaryAlign = text .AlignCenter
48+ textOpts .GeoM .Translate (float64 (textXPos ), float64 (textYPos ))
49+ text .Draw (screen , textValue , & text.GoTextFace {
50+ Source : mplusFaceSource ,
51+ Size : getFontSize (value ),
52+ }, textOpts )
53+ }
54+ }
1855
1956func (g * GameLayout ) Draw (screen * ebiten.Image ) {
2057 // 背景色
2158 screen .Fill (color.RGBA {250 , 248 , 239 , 255 })
2259 // 畫 4x4 格子
2360 for row := 0 ; row < gridSize ; row ++ {
2461 for col := 0 ; col < gridSize ; col ++ {
25- op := & ebiten.DrawImageOptions {}
26- x := padding + col * (tileSize + padding )
27- y := padding + row * (tileSize + padding )
28- rect := ebiten .NewImage (tileSize , tileSize )
29- rect .Fill (color.RGBA {205 , 193 , 180 , 255 })
30- op .GeoM .Translate (float64 (x ), float64 (y ))
31- screen .DrawImage (rect , op )
62+ // 取出值
63+ value := g .gameInstance .Data (row , col )
64+ // 畫格子背景
65+ g .drawCell (screen , value , row , col )
66+ // 畫文字
67+ g .drawTileText (screen , value , row , col )
3268 }
3369 }
3470}
@@ -41,6 +77,8 @@ func (g *GameLayout) Update() error {
4177 return nil
4278}
4379
44- func NameGameLayout () * GameLayout {
45- return & GameLayout {}
80+ func NameGameLayout (gameInstance * game.Game ) * GameLayout {
81+ return & GameLayout {
82+ gameInstance : gameInstance ,
83+ }
4684}
0 commit comments