概要
wsl(wsl2じゃない)で、elixirやってみた。
練習問題やってみた。
練習問題
Livebookの、kino.jsで、じゃんけんを書け。
喋らせよ。
サンプルコード
defmodule KinoHTML.Janken do
use Kino.JS
use Kino.JS.Live
def new(ans) do
Kino.JS.Live.new(__MODULE__, ans)
end
def init(ans, ctx) do
{:ok, assign(ctx, ans: ans)}
end
def handle_connect(ctx) do
{:ok, ctx.assigns.ans, ctx}
end
def handle_event("gu", _, ctx) do
ans = Janken.pon("0")
{:noreply, res(ctx, ans)}
end
def handle_event("choki", _, ctx) do
ans = Janken.pon("1")
{:noreply, res(ctx, ans)}
end
def handle_event("pa", _, ctx) do
ans = Janken.pon("2")
{:noreply, res(ctx, ans)}
end
defp res(ctx, ans) do
broadcast_event(ctx, "update", ans)
ctx
end
asset "main.js" do
"""
export function init(ctx, ans) {
ctx.root.innerHTML = `
<div id="ans"></div>
<button id="bt0">グー</button>
<button id="bt1">チョキ</button>
<button id="bt2">パー</button>
`;
const ansEl = document.getElementById("ans");
const bt0 = document.getElementById("bt0");
const bt1 = document.getElementById("bt1");
const bt2 = document.getElementById("bt2");
ansEl.innerHTML = ans;
talk(ans);
ctx.handleEvent("update", (ans) => {
ansEl.innerHTML = ans;
talk(ans);
});
bt0.addEventListener("click", (event) => {
ctx.pushEvent("gu");
});
bt1.addEventListener("click", (event) => {
ctx.pushEvent("choki");
});
bt2.addEventListener("click", (event) => {
ctx.pushEvent("pa");
});
function talk(src) {
var msg = new SpeechSynthesisUtterance();
msg.text = src;
msg.lang = "ja-JP";
msg.rate = 1.0;
msg.pitch = 0.8;
window.speechSynthesis.speak(msg);
}
}
"""
end
end
KinoHTML.Janken.new("じゃんけん、しよ")
以上。