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 その160

Last updated at Posted at 2025-03-13

概要

wsl(wsl2じゃない)で、elixirやってみた。
練習問題やってみた。

練習問題

Livebookの、kino.jsで、じゃんけんを書け。

setup

Mix.install([
  {:kino, "~> 0.15.0"}
])

写真

image.png

サンプルコード

defmodule Janken do
	def hand(c) do
		cond do
		c == 0 ->
			"グー"
		c == 1 ->
			"チョキ"
		c == 2 ->
			"パー"
		:else ->
			"うそ"
		end
	end
	def judge(a, b) do
		cond do
		a == b ->
			"あいこ"
		a == 0 && b == 1 ->
			"あなたの勝ち"
		a == 1 && b == 2 ->
			"あなたの勝ち"
		a == 2 && b == 0 ->
			"あなたの勝ち"
		a == 0 && b == 2 ->
			"あなたの負け"
		a == 1 && b == 0 ->
			"あなたの負け"
		a == 2 && b == 1 ->
			"あなたの負け"
		end
	end
	def pon(a) do
		res = ""
		{a, _} = a
			|> Integer.parse()
		res = res <> hand(a) <> "と"
		b = 0..2
			|> Enum.random()
		res = res <> hand(b) <> "で、"
		res = res <> judge(a, b)
		res
	end
end


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;
			ctx.handleEvent("update", (ans) => {
				ansEl.innerHTML = ans;
			});
			bt0.addEventListener("click", (event) => {
				ctx.pushEvent("gu");
			});
			bt1.addEventListener("click", (event) => {
				ctx.pushEvent("choki");
			});
			bt2.addEventListener("click", (event) => {
				ctx.pushEvent("pa");
			});
		}
		"""
	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?