examples/blocks: Fix initializing fonts not to depend on init() order

https://golang.org/ref/spec#Package_initialization
It is expected that init() is executed in file name order,
but this is not 100%.
This commit is contained in:
Hajime Hoshi 2018-03-17 01:56:23 +09:00
parent 530041b4f2
commit d8ba49eaab

View File

@ -32,27 +32,31 @@ const (
) )
var ( var (
arcadeFonts = map[int]font.Face{} arcadeFonts map[int]font.Face
) )
func init() { func getArcadeFonts(scale int) font.Face {
tt, err := truetype.Parse(fonts.ArcadeN_ttf) if arcadeFonts == nil {
if err != nil { tt, err := truetype.Parse(fonts.ArcadeN_ttf)
log.Fatal(err) if err != nil {
} log.Fatal(err)
}
for i := 1; i <= 4; i++ { arcadeFonts = map[int]font.Face{}
const dpi = 72 for i := 1; i <= 4; i++ {
arcadeFonts[i] = truetype.NewFace(tt, &truetype.Options{ const dpi = 72
Size: float64(arcadeFontBaseSize * i), arcadeFonts[i] = truetype.NewFace(tt, &truetype.Options{
DPI: dpi, Size: float64(arcadeFontBaseSize * i),
Hinting: font.HintingFull, DPI: dpi,
}) Hinting: font.HintingFull,
})
}
} }
return arcadeFonts[scale]
} }
func textWidth(str string) int { func textWidth(str string) int {
b, _ := font.BoundString(arcadeFonts[1], str) b, _ := font.BoundString(getArcadeFonts(1), str)
return (b.Max.X - b.Min.X).Ceil() return (b.Max.X - b.Min.X).Ceil()
} }
@ -64,8 +68,8 @@ func drawTextWithShadow(rt *ebiten.Image, str string, x, y, scale int, clr color
offsetY := arcadeFontBaseSize * scale offsetY := arcadeFontBaseSize * scale
for _, line := range strings.Split(str, "\n") { for _, line := range strings.Split(str, "\n") {
y += offsetY y += offsetY
text.Draw(rt, line, arcadeFonts[scale], x+1, y+1, shadowColor) text.Draw(rt, line, getArcadeFonts(scale), x+1, y+1, shadowColor)
text.Draw(rt, line, arcadeFonts[scale], x, y, clr) text.Draw(rt, line, getArcadeFonts(scale), x, y, clr)
} }
} }