Lingara Lingara 說明文件 學習指南 API 函式庫 應用程式 起造 嵌入 網頁版
語言: 閩南語

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