1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

wslでelixir その161

Last updated at Posted at 2025-03-15

概要

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("じゃんけん、しよ")


以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?