1
1
package layout
2
2
3
3
import (
4
+ "fmt"
4
5
"image/color"
5
6
6
7
"github.com/hajimehoshi/ebiten/v2"
8
+ "github.com/hajimehoshi/ebiten/v2/text/v2"
9
+ "github.com/leetcode-golang-classroom/2048-game/internal/game"
7
10
)
8
11
9
12
const (
@@ -14,21 +17,54 @@ const (
14
17
WinHeight = tileSize * gridSize + padding * (gridSize + 1 )
15
18
)
16
19
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
+ }
18
55
19
56
func (g * GameLayout ) Draw (screen * ebiten.Image ) {
20
57
// 背景色
21
58
screen .Fill (color.RGBA {250 , 248 , 239 , 255 })
22
59
// 畫 4x4 格子
23
60
for row := 0 ; row < gridSize ; row ++ {
24
61
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 )
32
68
}
33
69
}
34
70
}
@@ -41,6 +77,8 @@ func (g *GameLayout) Update() error {
41
77
return nil
42
78
}
43
79
44
- func NameGameLayout () * GameLayout {
45
- return & GameLayout {}
80
+ func NameGameLayout (gameInstance * game.Game ) * GameLayout {
81
+ return & GameLayout {
82
+ gameInstance : gameInstance ,
83
+ }
46
84
}
0 commit comments