#189: Phoenix LiveView Tutorial Part 13

Published January 27, 2024 1m 57s

In our last episode, we put the final piece of our guess results in place - updating the background colors of our keyboard to reflect the status of the letter in the guess.

Our game works and is playable, but we have one small improvement we can make. When we finish a game the only way to start a new game is to refresh the page. Let’s update that so that once a game ends, a new one is started automatically for the player.

To do that we’ll open our WordLive.Index LiveView and to start a new game we’ll simply send a message to our LiveView after a certain amount of time, telling it to start a new game. We’ll create a new callback handle_info that will pattern match on the :new_game event. And it will take the socket. Then inside the callback, we’ll return a :noreply tuple and we’ll call push_navigate, which annotates the socket for navigation to another LiveView. However, in our case, we’ll use it to remount our same LiveView. Then we’ll go to our guess scenarios and when there’s a correct guess we’ll start a new game by sending a message with Process.send_after to self(), which is our current LiveView, including the message :new_game. Let’s have our new game start in 7500 milliseconds or 7.5 seconds. And we’ll add the same code for when a player runs out of guesses.

lib/werdle_web/components/game_board/keycap_component.exdefmodule WerdleWeb.WordLive.Index do

  ...

  @impl true
  def handle_info(:new_game, socket) do
    {:noreply, push_navigate(socket, to: "/")}
  end

  ...

  def handle_event("enter", _params, socket) do
    changeset = socket.assigns.changeset
    guess_row = socket.assigns.current_guess
    solve = socket.assigns.solve

    with {:ok, _} <- Game.validate_guess(changeset, guess_row),
         {:correct, _} <- Game.check_guess_correctness(changeset, guess_row, solve.name) do
      Process.send_after(self(), :new_game, 7500)
      {:noreply, handle_correct_guess(socket)}

    else
      {:error, error_message} ->
        {:noreply, handle_invalid_guess(socket, error_message)}

      {:incorrect, _} when guess_row == 5 ->
        Process.send_after(self(), :new_game, 7500)
        {:noreply, handle_game_over(socket)}

      {:incorrect, _} ->
        {:noreply, handle_incorrect_guess(socket)}

    end
  end

  ...
end

Great, now let’s go back to the browser and play a quick game. Now when we guess correctly it automatically starts a new game for us. A player doesn’t have to worry about anything other than making guesses.

Ready to Learn More?

Subscribe to get access to all episodes and exclusive content.

Subscribe Now