Lingara Lingara 文档 学习指南 API 库 应用 构建 嵌入 网页版
语言: 中文简体

Godot

本页译自英文。如两者有出入,以英文页面为准。 阅读英文页面

Godot 提供两种语言,Lingara 为每一种都准备了工具包。GDScript 游戏使用 Lingara 插件。Godot C# 游戏使用 Lingara.Embed,也就是 Unity 游戏所用的同一个软件包。在一个项目中只使用其中之一,绝不同时使用两者。下方的标签页分别展示了两者。

安装

GDScript。 从 Godot Asset Library 安装 Lingara 插件,然后在“项目设置”的“插件”中启用它。启用后会添加一个名为 Lingara 的自动加载,每个场景都可以通过 /root/Lingara 访问它。

C#。 把 Lingara.Embed 作为包引用添加到你的项目中。下方的示例节点 LingaraEmbedNode 不属于该软件包:把它的源代码加入你的项目,并把它放进一个场景中。

从你的服务器获取令牌

两个工具包都不持有密钥。当核心需要令牌时,会向你自己的服务器请求,服务器用服务器工具包签发一个令牌,并返回令牌及其过期时间。

使用插件时,在“项目设置”中设置你的服务器的令牌路由,Lingara 会在自己的线程上调用它。如果该路由需要玩家的会话,请改为在运行时设置,因为项目设置会随你的导出一起发布。或者连接 token_needed,自己响应每一个请求。使用 C# 时,每当客户端请求令牌,示例节点都会向你的令牌路由发送 POST 请求。无论哪种方式,都用 token_unavailable 或 TokenUnavailable 报告失败,让正在等待的调用立即失败。

每帧处理事件

核心在自己的线程上执行网络 I/O。插件的自动加载每帧清空一次队列,并为每个事件发出一个信号,所以你只需连接游戏需要的信号,无需自己清空任何东西。C# 节点在 _process 中清空队列,每帧最多 256 个事件,并把每个事件重新作为 Godot 信号发出。

同样的信号也承载流式的 NPC 回复(见 NPC 对话)和练习更新(见练习结果)。

<PackageReference Include="Lingara.Embed" Version="0.1.0-alpha.6" />
代码示例语言

Godot C#

// Your own server mints the token: never put a client secret in a game. The
// continuation may run off the main thread, which the client allows.
private async Task FetchToken()
{
    try
    {
        using var response = await Http.PostAsync(TokenUrl, new StringContent("{}"));
        response.EnsureSuccessStatusCode();
        using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
        Client?.ProvideToken(body.RootElement.GetProperty("token").GetString(), body.RootElement.GetProperty("expires_at").GetString());
    }
    catch (Exception e) when (e is HttpRequestException || e is JsonException || e is KeyNotFoundException)
    {
        Client?.TokenUnavailable(e.Message); // fail the waiting calls now
    }
}

GDScript

# The common case: set Project Settings > lingara/token_url to your server's
# token route, which answers exactly {"token", "expires_at"}. Lingara POSTs to
# it on its own thread whenever it needs a token. If the route needs the
# player's session, set it at run time instead (never in ProjectSettings,
# which ships inside the export):
func use_my_session(session_cookie: String) -> void:
	lingara.set_token_endpoint("https://game.example.com/lingara-token", {"cookie": session_cookie})


# Or answer each token_needed yourself, with whatever login your game has.
func _on_token_needed(_request: int, _reason: String) -> void:
	var http := HTTPRequest.new()
	add_child(http)
	http.request("https://game.example.com/lingara-token", [], HTTPClient.METHOD_POST, "{}")
	var reply: Array = await http.request_completed
	http.queue_free()
	var body: Variant = JSON.parse_string((reply[3] as PackedByteArray).get_string_from_utf8())
	if reply[1] == 200 and body is Dictionary:
		lingara.provide_token(body["token"], body["expires_at"])
	else:
		lingara.token_unavailable("the token route answered %d" % reply[1])
代码示例语言

Godot C#

public override void _Process(double delta)
{
    if (Client == null) return;
    events.Clear();
    Client.Drain(events); // at most 256 a frame; the rest wait for the next
    foreach (var e in events)
    {
        switch (e)
        {
            case EmbedEvent.TokenNeeded _: _ = FetchToken(); break;
            case EmbedEvent.NpcTurn { Update: NpcTurnUpdate.Fragment f } t:
                EmitSignal(SignalName.NpcTurnFragment, t.Dialogue.Value, t.Request.Value, f.Text); break;
            case EmbedEvent.NpcTurn { Update: NpcTurnUpdate.Finished f } t:
                EmitSignal(SignalName.NpcTurnFinished, t.Dialogue.Value, t.Request.Value, f.Text); break;
            case EmbedEvent.Practice p: EmitSignal(SignalName.PracticeChanged, p.Session.Value, p.Snapshot.Phase.ToString()); break;
            case EmbedEvent.Failed f: EmitSignal(SignalName.Failed, f.Error.KindName, f.Error.Message, f.Error.Request?.Value ?? 0); break;
            case EmbedEvent.Log log: GD.Print($"[lingara] {log.Level} {log.Target}: {log.Message}"); break;
        }
    }
}

GDScript

# The Lingara autoload the plugin adds, reached by path and typed, so every
# call and signal below is checked against LingaraEmbed.
@onready var lingara: LingaraEmbed = get_node("/root/Lingara")

# Enable the plugin (Project > Project Settings > Plugins): it adds the
# Lingara autoload, which drains the core once per frame and emits one signal
# per event. Connect the signals your game needs; you never call drain.
func _ready() -> void:
	lingara.token_needed.connect(_on_token_needed)
	lingara.event_received.connect(_on_event)
	lingara.error_raised.connect(func(error: Dictionary) -> void: push_warning(error.message))
	lingara.practice_changed.connect(_on_practice_changed)
	lingara.practice_finished.connect(_on_practice_finished)
	mei.replied.connect(_on_mei_replied)


func _on_event(_id: String, event_type: String, _created_at: String, data: Dictionary) -> void:
	if event_type == "lesson_plan.ready":
		print("a plan is ready: ", data.get("plan_id"))