a11y
game/a11y 基于 NSGo 公开 API 提供游戏无障碍基础组件:对话与方向性音效实时字幕、色盲友好调色板与色觉缺陷(CVD)模拟、持久化辅助选项,以及适配屏幕阅读器的原生菜单。
import "github.com/nsgo-dev/game/packages/game/a11y"
持久化辅助选项(Assist)
NewAssist(cx, key) 将无障碍偏好以响应式状态保存在 core.Storage 中,跨启动自动保留并在修改时刷新 NSGo 视图:
assist := a11y.NewAssist(cx, "a11y")
// 在 game.Loop.Update 中按 GameSpeed(0.25..1.0)缩放模拟步长 dt:
loop := &game.Loop{
Update: func(dt time.Duration) {
sim.Step(assist.ScaleDT(dt))
},
}
*Assist 支持的持久化选项(亦可通过 Snapshot()、Apply(opts) 与 Reset() 整体读写 AssistOptions):
| 选项 | 范围 / 默认值 | 说明 |
|---|---|---|
GameSpeed / ScaleDT |
0.25–1.0(1.0) |
缩放游戏逻辑 dt,不影响显示刷新率。 |
ReduceMotion |
bool |
未设置时默认读取操作系统的“减弱动态效果”偏好。 |
HighContrast |
bool |
未设置时默认读取系统高对比度偏好;开启后 assist.Palette() 返回 VisionHighContrast。 |
ColorVision |
ColorVision |
选择 VisionNormal、VisionProtanopia、VisionDeuteranopia、VisionTritanopia 或 VisionHighContrast。 |
TextScale |
1.0–2.0(1.0) |
字体缩放倍率,CaptionsView 与 AccessibleMenu 自动应用。 |
Invincibility、AutoAim、HoldToToggle |
bool |
供战斗与输入层读取的辅助开关。 |
CaptionsEnabled、SFXCaptionsEnabled |
bool |
分别控制对话字幕与音效字幕开关。 |
实时字幕(CaptionTrack 与 CaptionsView)
通过 CaptionTrack 推送定时对话、带方向指示的音效、音乐提示或重要告警,在 game.Loop 中推进计时,并用 CaptionsView 作为原生 NSGo 视图叠加显示:
captions := a11y.NewCaptionTrack(cx)
// 玩家右侧传来爆炸声(direction 范围 [-1, 1]):
if assist.SFXCaptionsEnabled() {
captions.ShowSFXAt("爆炸声", 0.8, 2500*time.Millisecond)
}
captions.ShowDialogue("向导", "小心前方的吊桥。", 3*time.Second)
// 在 game.Loop.Update 中:
captions.Update(dt)
// 在根 Stack 视图中叠加:
a11y.CaptionsView(cx, captions, a11y.CaptionStyle{Assist: assist})
Caption.Format() 会自动格式化说话人("向导: ...")、音效方向标记("[爆炸声 →]")与音乐提示("♪ ...")。可用 Dismiss(id) 或 Clear() 提前清除条目。
色盲友好调色板与 CVD 模拟
PaletteFor(mode) 返回基于 Okabe-Ito / Wong 方案的语义调色板 Palette(含 Player、Ally、Enemy、Hazard、Pickup、Neutral、Background、Foreground、Highlight、Accent)。可在测试或运行时主题中使用 Simulate、ContrastRatio 与 EnsureContrast:
pal := assist.Palette()
simEnemy := a11y.Simulate(pal.Enemy, a11y.VisionDeuteranopia)
ratio := a11y.ContrastRatio(pal.Foreground, pal.Background)
readable := a11y.EnsureContrast(accentColor, pal.Background, 4.5)
_, _, _ = simEnemy, ratio, readable
屏幕阅读器菜单(AccessibleMenu)
用 AccessibleMenu 渲染暂停、设置与辅助选项菜单,内置原生无障碍角色(RoleMenu、RoleMenuItem、RoleMenuItemCheckbox)、完整键盘导航(Up/Down/Home/End/Return/Space/Escape)及 cx.Announce 实时朗读播报:
a11y.AccessibleMenu(cx, a11y.MenuProps{
Label: "辅助选项",
Assist: assist,
OnClose: closeMenu,
Items: []a11y.MenuItem{
{
ID: "reduce-motion",
Label: "减弱动态效果",
Checked: assist.ReduceMotion,
OnSelect: func() { _ = assist.SetReduceMotion(!assist.ReduceMotion()) },
},
{
ID: "game-speed",
Label: "游戏速度",
Value: func() string { return fmt.Sprintf("%d%%", int(assist.GameSpeed()*100)) },
OnSelect: cycleGameSpeed,
},
},
})