首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Golang语言情怀--第134期 Go语言Ebiten引擎全栈游戏开发:第5节:fonts实例分析

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

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

Ebiten框架实例fonts

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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
运行
AI代码解释
复制
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
运行
AI代码解释
复制
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 删除。

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

评论
登录后参与评论
暂无评论
推荐阅读
【DB笔试面试274】在Oracle中,什么是延迟段创建(Deferred Segment Creation)?
在Oracle中,什么是延迟段创建(Deferred Segment Creation)?
AiDBA宝典
2022/02/22
8220
11g的延迟段功能
1. 初始创建表时就需要分配空间,自然会占用一些时间,如果初始化多张表,这种影响就被放大。
bisal
2019/01/29
5170
Oracle deallocate unused释放高水位空间
deallocate unused :仅适用于释放HWM高水位以上的空间,而无法释放高水位以下的空间;比如对表预分配的空间
星哥玩云
2022/08/17
7800
一个用户创建引发的权限控制问题
需求描述:要求开发库创建一个新用户A(默认表空间TBS_1),由于这库是共享库,还有其他schema(示例:表空间TBS_2)被其他组的开发人员使用,需要避免使用A用户的开发人员,利用create table t(col name) tablespace tbs_2通过指定表空间的方式在tbs_2上创建表,即禁止用户A可以在tbs_2表空间上进行操作。
bisal
2019/01/30
5900
【OCP最新题库解析(052)--题49】Examine these facts about a database.
该系列专题为2018年4月OCP-052考题变革后的最新题库。题库为小麦苗解答,若解答有不对之处,可留言,也可联系小麦苗进行修改。
AiDBA宝典
2019/09/29
4540
Oracle中的段(r10笔记第81天)
Oracle的体系结构中,关于存储结构大家应该都很熟悉了。 估计下面这张图大家都看得熟悉的不能再熟悉了。 简单来说,里面的一个重要概念就是段,如果是开发同学,可能每次听到这里都会有些模糊,好像懂,
jeanron100
2018/03/21
6170
Oracle中的段(r10笔记第81天)
SQL 基础-->创建和管理表
(列名 数据类型 [ default 默认值] [ 约束条件] [ , ......] )
Leshami
2018/08/07
1.1K0
Oracle move和shrink释放高水位空间
  alter table TABLE_NAME shrink space [compact|cascate]
星哥玩云
2022/08/17
1.9K0
对象迁移表空间引出的三个小问题
我们有一个开发库,默认表空间是TEST_TBS,但今天查看开发库的时候,发现有些表和字段并不在用户默认使用的表空间中,而在USERS表空间,之所以可能是之前开发人员执行SQL是从其他库复制过来的,连通tablespace USERS名称一块复制了,为了规范,就需要将这些对象转移下表空间,期间碰见了几个常见的小问题,值得记录一下。
bisal
2019/01/30
5500
Oracle常用数据字典表
Oracle常用数据字典表      查看当前用户的缺省表空间   SQL>select username,default_tablespace from user_users;   查看当前用户的角色   SQL>select * from user_role_privs;   查看当前用户的系统权限和表级权限   SQL>select * from user_sys_privs;   SQL>select * from user_tab_privs;   查看用户下所有的表   
阿新
2018/04/12
7400
海量数据迁移之外部表并行抽取(99天)
在10g开始的新特性中,外部表是一个不容忽视的好工具。对于大型项目中海量数据使用sqlloader是一种全新的方式,不过很明显,sqlloader的可扩展性更强,但是基于oracle平台的数据迁移来说,外部表的性能也不错。对于数据迁移来说也是一个很好的方案。 使用外部表来做数据迁移,可以“动态”加载数据,能够很方便的从数据库中加载数据,对于数据校验来说就显得很有优势了,而对于sqlloader来说,可能得等到数据加载的时候才知道是不是有问题,如果对于数据的准确性要求极高,可以使用外部表动态加载数据到备库,和
jeanron100
2018/03/14
1.7K0
海量数据迁移之分区并行抽取(r2笔记53天)
在之前的章节中分享过一些数据迁移中并行抽取的细节,比如一个表T 很大,有500G的数据,如果开启并行抽取,默认数据库中并行的最大值为64,那么生成的dump文件最50多为64个,每个dump文件就是7.8G,还是不小,况且在做数据抽取的时候,资源被极大的消耗,如果资源消耗紧张,可能可用的并行资源还不到64个。那么dump文件可能比7G还要大得多。 如果换一步来说,我们尝试调高并行的参数,可以支持100个并行,那么每个dump文件也有5G,也没有太大的改善。 所以自己在斟酌后考虑使用分区加并行的思想来做大表的
jeanron100
2018/03/14
1.2K0
Oracle数据逻辑迁移综合实战篇
本次需求: 指定用户表结构迁移,所有表需要数据(因为此用户下的数据规模是10T的级别,所以想完全迁移不现实,最终确定为大表迁移部分数据,小表迁移全部数据)。 至于大表和小表的界定,研发侧不能提供,需要DBA自行评估划分。
Alfred Zhao
2019/05/24
8800
【Oracle笔记】最详细的操作命令大全(牛人高阶版)
文章目录 一、Oracle数据库连接 1、三种以系统管理员身份连接数据库的方式 2、启动sqlplus,连接数据库服务器 3、用系统管理员,查看当前数据库有几个用户连接 4、listen监听服务 5、Oralce实例服务 二、Oracle用户管理 1、查看系统拥有哪些用户 2、显示当前连接用户 3、新建用户并授权 4、修改用户密码 5、授权用户可以访问数据库所有表 6、授权用户操作其他用户的表 7、查找用户下的所有表 8、查看当前用户的缺省表空间 9、查看当前用户的角色 10、查看当前用户的系统权限和表级权
程序员云帆哥
2022/05/12
7600
导入导出的两个小错误
在使用exp/imp导出导入,经常会碰见各种的问题,前两天某公众号发了篇《IMP-00009:异常结束导出文件解决方案》,介绍了导入出现IMP-00009错误的解决方案,讲了各种场景,可以参考。
bisal
2019/08/16
1.3K0
【开发日记】Oracle 常用操作及解决方案
此表分区是两个案例,根据某个字段的值的大小范围进行分区或者根据时间范围进行分区
全栈开发日记
2023/09/25
3350
【开发日记】Oracle 常用操作及解决方案
探索索引的奥秘 - 索引的属性
索引是一种奇特的对象,他就像一把双刃剑,用好了可以提高性能,用不好就可能会影响性能,但如何才能用好索引?
bisal
2019/01/29
6230
【循序渐进Oracle】Oracle段空间管理技术
在Oracle数据库内部,对象空间是以段的形式(Segment)存在和管理的,通过不同的段类型Oracle将段区分开来,在Oracle 9i中,主要的段类型有: 当一个段被创建时,区间(Extent)
数据和云
2018/03/07
1.9K0
【循序渐进Oracle】Oracle段空间管理技术
ORA-01950 报错解决实例
结论先行: 1,此表的创建用户权限无问题,表上有其他用户创建的索引 2,报错时,这个索引的创建用户在表空间上无权限或配额 3,dba权限的回收,会导致UNLIMITED TABLESPACE系统权限被回收 4,处理方法:给索引创建用户授予权限或配额 grant UNLIMITED TABLESPACE to username; 或 alter user username quota unlimited on tablespace_name;
星哥玩云
2022/08/18
1.2K0
IMP-00009:异常结束导出文件解决方案
最近在测试环境的一个Oracle数据库上面,使用exp将表导出没有问题,而将导出的文件使用imp导入时却出现了如下错误。
数据和云
2019/07/30
2.2K0
相关推荐
【DB笔试面试274】在Oracle中,什么是延迟段创建(Deferred Segment Creation)?
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档