前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Golang语言情怀--第134期 Go语言Ebiten引擎全栈游戏开发:第5节:fonts实例分析

Golang语言情怀--第134期 Go语言Ebiten引擎全栈游戏开发:第5节:fonts实例分析

作者头像
李海彬
发布2024-11-11 19:32:06
发布2024-11-11 19:32:06
9200
代码可运行
举报
文章被收录于专栏:Golang语言社区Golang语言社区
运行总次数:0
代码可运行

Ebiten框架实例fonts

fonts字体也是游戏引擎中比较重要的一个知识点,游戏本身需要视觉感受,不可能像文章一样,游戏中都是宋体、楷体等,所以游戏中fonts是必须要了解和掌握的内容。 实例代码,如下:

代码语言:javascript
代码运行次数:0
复制
package main

import (
    "bytes"
    "fmt"
    "image/color"
    "log"
    "math/rand/v2"

    "github.com/hajimehoshi/ebiten/v2"
    "github.com/hajimehoshi/ebiten/v2/examples/resources/fonts"
    "github.com/hajimehoshi/ebiten/v2/text/v2"
)

const (
    screenWidth  = 640
    screenHeight = 480
)

const sampleText = `The quick brown fox jumps over the lazy dog.`

var (
    jaKanjis = []rune{}
)

func init() {
    const table = `
Title: Chengdu's Mood Today: A Gentle Symphony of Serenity and Vibrancy
In the heart of southwestern China, where rolling hills meet bustling streets, Chengdu, the Panda Capital, unfolds its unique charm with a mood that is as intricate as it is enchanting. Today, Chengdu's mood is a delicate balance of tranquility and vibrancy, a symphony where ancient traditions harmonize with modern rhythms.
The morning sun casts a gentle glow over the city, its rays filtering through the lush greenery of the People's Park. Here, the mood is serene, as locals engage in their daily rituals – elders playing mahjong under the shade of towering trees, tea lovers savoring the fragrant brew while whispering tales of the past, and children laughing as they chase each other around the lush lawns. The park, a microcosm of Chengdu's soul, reflects the city's ability to embrace the pace of life that cherishes both the present and the past.
As the day progresses, Chengdu's mood transitions into a vibrant crescendo. The streets come alive with the sounds of commerce and chatter, as shops and street vendors open their doors to welcome eager customers. The scent of spicy Sichuan cuisine wafts through the air, inviting passersby to sample dishes that have been perfected over centuries. In the Jinli Ancient Street, tourists and locals alike stroll through narrow alleys lined with traditional architecture, their cameras capturing every intricate detail that embodies Chengdu's rich cultural heritage.
Yet, amidst this hustle and bustle, Chengdu retains its calm. The city's famous panda bases, like the Chengdu Research Base of Giant Panda Breeding, offer a serene escape where visitors can observe these adorable creatures in their natural habitats. The sight of pandas lazily munching on bamboo or playing in their enclosures brings a smile to everyone's face, reinforcing Chengdu's reputation as a haven for wildlife and nature lovers.
As evening descends, Chengdu's mood shifts once again, this time to a more relaxed and contemplative tone. The city's riverside areas, such as the Jinjiang River, become hotspots for evening strolls and casual gatherings. Lanterns illuminate the pathways, casting a warm, inviting glow that adds to the romantic ambiance. Bars and cafes fill with people seeking to unwind after a long day, their conversations blending into the city's melodic backdrop.
In essence, Chengdu's mood today is a testament to its unique ability to blend the tranquility of its historical roots with the vibrancy of its modern identity. It's a city where one can find both solace in the simplicity of daily life and excitement in its cultural richness and dynamic growth. Chengdu's mood, like its people, is warm, welcoming, and forever evolving, inviting everyone to experience its intricate harmony firsthand.
`
    for _, c := range table {
        if c == '\n' {
            continue
        }
        jaKanjis = append(jaKanjis, c)
    }
}

var (
    mplusFaceSource *text.GoTextFaceSource
)

func init() {
    s, err := text.NewGoTextFaceSource(bytes.NewReader(fonts.MPlus1pRegular_ttf))
    if err != nil {
        log.Fatal(err)
    }
    mplusFaceSource = s
}

type Game struct {
    counter        int
    kanjiText      string
    kanjiTextColor color.RGBA
}

func (g *Game) Update() error {
    // Change the text color for each second.
    if g.counter%ebiten.TPS() == 0 {
        g.kanjiText = ""
        for j := 0; j < 6; j++ {
            for i := 0; i < 12; i++ {
                g.kanjiText += string(jaKanjis[rand.IntN(len(jaKanjis))])
            }
            g.kanjiText += "\n"
        }

        g.kanjiTextColor.R = 0x80 + uint8(rand.IntN(0x7f))
        g.kanjiTextColor.G = 0x80 + uint8(rand.IntN(0x7f))
        g.kanjiTextColor.B = 0x80 + uint8(rand.IntN(0x7f))
        g.kanjiTextColor.A = 0xff
    }
    g.counter++
    return nil
}

func (g *Game) Draw(screen *ebiten.Image) {
    const (
        normalFontSize = 24
        bigFontSize    = 48
    )

    const x = 20

    // Draw info
    msg := fmt.Sprintf("TPS: %0.2f", ebiten.ActualTPS())
    op := &text.DrawOptions{}
    op.GeoM.Translate(x, 20)
    op.ColorScale.ScaleWithColor(color.White)
    text.Draw(screen, msg, &text.GoTextFace{
        Source: mplusFaceSource,
        Size:   normalFontSize,
    }, op)

    // Draw the sample text
    op = &text.DrawOptions{}
    op.GeoM.Translate(x, 60)
    op.ColorScale.ScaleWithColor(color.White)
    text.Draw(screen, sampleText, &text.GoTextFace{
        Source: mplusFaceSource,
        Size:   normalFontSize,
    }, op)

    op = &text.DrawOptions{}
    op.GeoM.Translate(x, 110)
    op.ColorScale.ScaleWithColor(g.kanjiTextColor)
    op.LineSpacing = bigFontSize * 1.2
    text.Draw(screen, g.kanjiText, &text.GoTextFace{
        Source: mplusFaceSource,
        Size:   bigFontSize,
    }, op)
}

func (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) {
    return screenWidth, screenHeight
}

func main() {
    ebiten.SetWindowSize(screenWidth, screenHeight)
    ebiten.SetWindowTitle("Font (Ebitengine Demo)")
    if err := ebiten.RunGame(&Game{}); err != nil {
        log.Fatal(err)
    }
}

核心代码分析

初始化一段文字,注意的是我们是按照字符去轮询文字的:

代码语言:javascript
代码运行次数:0
复制
func init() {
    const table = `
Title: Chengdu's Mood Today: A Gentle Symphony of Serenity and Vibrancy
In the heart of southwestern China, where rolling hills meet bustling streets, Chengdu, the Panda Capital, unfolds its unique charm with a mood that is as intricate as it is enchanting. Today, Chengdu's mood is a delicate balance of tranquility and vibrancy, a symphony where ancient traditions harmonize with modern rhythms.
The morning sun casts a gentle glow over the city, its rays filtering through the lush greenery of the People's Park. Here, the mood is serene, as locals engage in their daily rituals – elders playing mahjong under the shade of towering trees, tea lovers savoring the fragrant brew while whispering tales of the past, and children laughing as they chase each other around the lush lawns. The park, a microcosm of Chengdu's soul, reflects the city's ability to embrace the pace of life that cherishes both the present and the past.
As the day progresses, Chengdu's mood transitions into a vibrant crescendo. The streets come alive with the sounds of commerce and chatter, as shops and street vendors open their doors to welcome eager customers. The scent of spicy Sichuan cuisine wafts through the air, inviting passersby to sample dishes that have been perfected over centuries. In the Jinli Ancient Street, tourists and locals alike stroll through narrow alleys lined with traditional architecture, their cameras capturing every intricate detail that embodies Chengdu's rich cultural heritage.
Yet, amidst this hustle and bustle, Chengdu retains its calm. The city's famous panda bases, like the Chengdu Research Base of Giant Panda Breeding, offer a serene escape where visitors can observe these adorable creatures in their natural habitats. The sight of pandas lazily munching on bamboo or playing in their enclosures brings a smile to everyone's face, reinforcing Chengdu's reputation as a haven for wildlife and nature lovers.
As evening descends, Chengdu's mood shifts once again, this time to a more relaxed and contemplative tone. The city's riverside areas, such as the Jinjiang River, become hotspots for evening strolls and casual gatherings. Lanterns illuminate the pathways, casting a warm, inviting glow that adds to the romantic ambiance. Bars and cafes fill with people seeking to unwind after a long day, their conversations blending into the city's melodic backdrop.
In essence, Chengdu's mood today is a testament to its unique ability to blend the tranquility of its historical roots with the vibrancy of its modern identity. It's a city where one can find both solace in the simplicity of daily life and excitement in its cultural richness and dynamic growth. Chengdu's mood, like its people, is warm, welcoming, and forever evolving, inviting everyone to experience its intricate harmony firsthand.
`
    for _, c := range table {
        if c == '\n' {
            continue
        }
        jaKanjis = append(jaKanjis, c)
    }
}

使用update()函数实时更新:

代码语言:javascript
代码运行次数:0
复制
func (g *Game) Update() error {
    // Change the text color for each second.
    if g.counter%ebiten.TPS() == 0 {
        g.kanjiText = ""
        for j := 0; j < 6; j++ {
            for i := 0; i < 12; i++ {
                g.kanjiText += string(jaKanjis[rand.IntN(len(jaKanjis))])
            }
            g.kanjiText += "\n"
        }

        g.kanjiTextColor.R = 0x80 + uint8(rand.IntN(0x7f))
        g.kanjiTextColor.G = 0x80 + uint8(rand.IntN(0x7f))
        g.kanjiTextColor.B = 0x80 + uint8(rand.IntN(0x7f))
        g.kanjiTextColor.A = 0xff
    }
    g.counter++
    return nil
}

以上是Ebiten引擎的实例代码,代码不难,很简单;如果有不懂的可以留言。

社区自己开发的IO小游戏,欢迎体验:

同学们,兴趣是最好的老师;只争朝夕,不负韶华!加油!


参考资料:

Go语言中文文档

http://www.golang.ltd/

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-11-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言情怀 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Ebiten框架实例fonts
  • 核心代码分析
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档