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,15 +32,17 @@ const (
) )
var ( var (
arcadeFonts = map[int]font.Face{} arcadeFonts map[int]font.Face
) )
func init() { func getArcadeFonts(scale int) font.Face {
if arcadeFonts == nil {
tt, err := truetype.Parse(fonts.ArcadeN_ttf) tt, err := truetype.Parse(fonts.ArcadeN_ttf)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
arcadeFonts = map[int]font.Face{}
for i := 1; i <= 4; i++ { for i := 1; i <= 4; i++ {
const dpi = 72 const dpi = 72
arcadeFonts[i] = truetype.NewFace(tt, &truetype.Options{ arcadeFonts[i] = truetype.NewFace(tt, &truetype.Options{
@ -50,9 +52,11 @@ func init() {
}) })
} }
} }
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)
} }
} }