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

Godot

這頁係對英文翻譯過來个。若係兩片無共樣,以英文頁為準。 看英文頁

Godot 提供兩種語言,Lingara 每種都有一隻套件。GDScript 遊戲用 Lingara 附加元件。Godot C# 遊戲用 Lingara.Embed,就係 Unity 遊戲用个同一隻套件包。一隻專案肚淨用其中一種,千萬毋好兩種共下用。下背个分頁顯示每種个做法。

安裝

GDScript. 從 Godot Asset Library 安裝 Lingara 附加元件,過後在 Project Settings, Plugins 肚將佢啟用。啟用以後會加一隻名喊 Lingara 个 autoload,每隻場景都做得在 /root/Lingara 尋到佢。

C#. 將 Lingara.Embed 當做套件參照加入你个專案。下背个範例節點 LingaraEmbedNode 毋係套件包个一部分:將佢个原始碼加入你个專案,再將佢放入一隻場景。

從你个伺服器拿權杖

兩隻套件都毋會保管密鑰。核心需要權杖个時節,會去問你自家个伺服器;你个伺服器用一隻伺服器套件簽發一隻權杖,再用權杖摎佢个到期時間來回應。

用附加元件个時節,在 Project Settings 肚設定你伺服器个權杖路由,Lingara 就會在佢自家个執行緒頂高呼叫佢。若係路由需要玩家个工作階段,就改在執行个時節設定,因為專案設定會跈等你匯出个檔案共下發布出去。抑係連接 token_needed,自家回應每隻請求。用 C# 个時節,用戶端愛討權杖,範例節點就會送請求到你个權杖路由。毋管哪一種,都用 token_unavailable 抑係 TokenUnavailable 回報失敗,恁樣在該等个呼叫就會馬上失敗。

每格處理事件

核心在佢自家个執行緒頂高行網路 I/O。附加元件个 autoload 每格將佢清一擺,每隻事件發出一隻訊號,所以你淨愛連接你个遊戲需要个訊號,永遠毋使自家清麼个。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"))