Lingara Lingara 說明文件 學習指南 API 函式庫 App 建立 嵌入 網頁版
語言: 繁體中文

Godot

本頁譯自英文。如兩者有出入,以英文頁面為準。 閱讀英文頁面

Godot 提供兩種語言,Lingara 為每一種都準備了套件。GDScript 遊戲使用 Lingara 外掛程式。Godot C# 遊戲使用 Lingara.Embed,也就是 Unity 遊戲所用的同一個 NuGet 套件。在一個專案中只使用其中之一,絕不同時使用兩者。下方的分頁分別示範了兩者。

安裝

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"))