Did someone solve the challenge in the first chapter of Programming Phoenix LiveView?

Hi,
I’m trying to solve the challenge in the first chapter of Programming Phoenix LiveView book. The challenge asks for altering the code so that a random number is set as the right guess and when the user clicks that number, it tells the user the number is correct.

Did anyone solve this challenge already?

I asked the same qusetion here five days ago, but didn’t yet get an answer.

1 Like

You have 4 tasks to do, none of which seems too difficult…

  1. generate a random number and put it into the socket
  2. check in handle event… You need to build live_patch links with the event and the value
  3. show a winning message when won… store a game status
  4. You can reuse this status to conditionally display reset button

Where do You have problem?

  1. socket |> assign(:number, :rand.uniform(10)) |> assign(:win, false) |> assign(:score, 0)
  2. def handle_event(“guess”, %{“value”=>value}, socket) do
    if socket.assigns.number == value do
    … :win → true, reset number, increase score
    else
    … You might hold a counter for wrong guess …
    end
    end
  3. simply check @win in the template, with conditional rendering of reset links…
  4. reuse 1 to reset the game
1 Like

But I see in your other post You have already similar code…

      <%= for n <- 1..10 do %>
        <a href="#" phx-click="guess" phx-value-number={n}><%= n %></a>
      <% end %>

I would not do this… but use live_patch instead.

The other error is a scoping error. You cannot set an outside scope value from within a block, but You can return value(s)

UPDATE: I saw solutions in the other post… @crispinb has already given You good advices.

1 Like

Thank you for your replies!
I’m not in the live_patch lesson yet and I don’t know how to use it.
I will follow your other suggestions and suggestions give by someone to the other post.