Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

じゃんけん

livebooks/90_janken.livemd

じゃんけん

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

手と結果の定義

hands = [
  {0, "グー"},
  {1, "チョキ"},
  {2, "パー"}
]
results = ["あいこ", "勝ち", "負け"]

手の選択

my_hand_input = Kino.Input.select("あなたの手", hands)
my_hand = Kino.Input.read(my_hand_input)
# ランダムに決定
opponents_hand = 0..2 |> Enum.random()
get_hand_name = fn hand ->
  hands |> Enum.at(hand) |> elem(1)
end
IO.puts("あなたの手: #{get_hand_name.(my_hand)}")
IO.puts("あいての手: #{get_hand_name.(opponents_hand)}")

勝敗判定

judge = fn x_hand, y_hand ->
  IO.puts("あなたの手: #{get_hand_name.(x_hand)}")
  IO.puts("あいての手: #{get_hand_name.(y_hand)}")
  result = rem(y_hand - x_hand, 3)
  result_name = Enum.at(results, result)
  IO.puts("結果: #{result_name}")
  result_name
end
judge.(my_hand, opponents_hand)

全ての組み合わせ

%{
  "あいての手\\あなたの手" => Enum.map(hands, &elem(&1, 1))
}
|> Map.merge(
  for {x_hand, x_hand_name} <- hands, into: %{} do
    {
      x_hand_name,
      Enum.map(hands, fn {y_hand, _} ->
        judge.(x_hand, y_hand)
      end)
    }
  end
)
|> Kino.DataTable.new()