こちらの続きです
1-25の数字押していくゲームを作りたいです
このコラムの範囲
- 時間測定
時間の表示
全問クリック後時間を止める
lib/num_web/live/user_live/index.ex
defmodule NumWeb.UserLive.Index do
use NumWeb, :live_view
@impl true
def mount(_params, _session, socket) do
Process.send_after(self(), :update, 25)
num =
1..25
|> Enum.shuffle()
questions =
num
|> Enum.shuffle()
questions = questions ++ [nil]
[question | questions] = questions
start_time = DateTime.utc_now()
socket = assign(socket, num: num)
|> assign(ok_num: [])
|> assign(questions: questions)
|> assign(question: question)
|> assign(start_time: start_time)
|> assign(time: nil)
{:ok, socket}
end
@impl true
def handle_info(:update, socket) do
start_time = socket.assigns[:start_time]
ok_num = socket.assigns[:ok_num]
time = if length(ok_num) < 25 do
Process.send_after(self(), :update, 25)
DateTime.diff(DateTime.utc_now, start_time, :microsecond) / 1000000
else
socket.assigns[:time]
end
socket = assign(socket, time: time)
{:noreply, socket}
end
@impl true
def handle_event("buttno", %{"no" => no}, socket) do
question = socket.assigns[:question]
|> Integer.to_string()
socket = if question == no do
ok_num = socket.assigns[:ok_num] ++ [no]
[question | questions] = socket.assigns[:questions]
assign(socket, ok_num: ok_num)
|> assign(questions: questions)
|> assign(question: question)
else
socket
end
{:noreply, socket}
end
end
lib/num_web/live/user_live/index.html.heex
<div class="w-28 h-28 m-2 bg-red-200 text-center">
<p class="pt-7 text-5xl text-red-700 "><%= @question %></p>
</div>
<p class="pt-7 text-5xl text-red-700 "><%= @time %></p>
<br>
<%= for {s, i} <- Enum.with_index(@num, 1) do %>
<%= if Enum.find_index(@ok_num, fn x -> Integer.to_string(s) == x end) == nil do %>
<div phx-click="buttno" phx-value-no={s} class="float-left w-28 h-28 m-2 bg-blue-200 text-center ">
<p class="pt-7 text-5xl text-blue-700 "><%= s %></p>
</div>
<% else %>
<div class="float-left w-28 h-28 m-2 bg-blue-100 text-center ">
</div>
<% end %>
<%= if rem(i, 5) == 0 do %>
<br>
<% end %>
<% end %>
現時点結果
今回はここまで
今後の課題
- リセットボタン