1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00

Clients subscribe to the game to get updates

This commit is contained in:
Daniel Barber 2021-07-13 19:28:19 -05:00
parent bbc1838d7e
commit f5c35de8d8

View File

@ -14,6 +14,8 @@ defmodule ChessWeb.BoardLive do
end
def mount(_params, %{"user_id" => user_id, "game_id" => game_id}, socket) do
ChessWeb.Endpoint.subscribe("game:#{game_id}")
user = Repo.get!(User, user_id)
game =
@ -40,6 +42,10 @@ defmodule ChessWeb.BoardLive do
}
end
def handle_info(%{event: "move", payload: state}, socket) do
{:noreply, assign(socket, state)}
end
defp handle_click(socket, file, rank) do
game = socket.assigns[:game]
board = game.board
@ -87,6 +93,8 @@ defmodule ChessWeb.BoardLive do
{:ok, %{game: game}} ->
board = Board.transform(game.board)
broadcast_move(game, board)
[
{:selected, nil},
{:available, []},
@ -98,4 +106,13 @@ defmodule ChessWeb.BoardLive do
[{:selected, nil}, {:available, []}]
end
end
defp broadcast_move(game, board) do
ChessWeb.Endpoint.broadcast_from(
self(),
"game:#{game.id}",
"move",
%{game: game, board: board}
)
end
end