Skip to content

Commit

Permalink
Make save game and backup game
Browse files Browse the repository at this point in the history
  • Loading branch information
William Guo authored and William Guo committed Feb 13, 2018
1 parent 4a31298 commit 1a65ffa
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions lib/memory/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ defmodule Memory.Application do
supervisor(MemoryWeb.Endpoint, []),
# Start your own worker by calling: Memory.Worker.start_link(arg1, arg2, arg3)
# worker(Memory.Worker, [arg1, arg2, arg3]),
worker(Memory.GameBackup, [])
]

# See https://hexdocs.pm/elixir/Supervisor.html
Expand Down
19 changes: 19 additions & 0 deletions lib/memory/game_backup.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
defmodule Memory.GameBackup do
use Agent

def start_link do
Agent.start_link(fn -> %{} end, name: __MODULE__)
end

def save(name, game) do
Agent.update(__MODULE__, fn state ->
Map.put(state, name, game)
end)
end

def load(name) do
Agent.get(__MODULE__, fn state ->
Map.get(state, name)
end)
end
end
3 changes: 2 additions & 1 deletion lib/memory_web/channels/games_channel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ defmodule MemoryWeb.GamesChannel do

def join("games:" <> name, payload, socket) do
if authorized?(payload) do
game = Game.new()
game = Memory.GameBackup.load(name) || Game.new()

socket =
socket
Expand All @@ -22,6 +22,7 @@ defmodule MemoryWeb.GamesChannel do
# by sending replies to requests from the client
def handle_in("click", %{"clickedIndex" => cardIndex}, socket) do
game = Game.handleClick(socket.assigns[:game], cardIndex)
Memory.GameBackup.save(socket.assigns[:name], game)
socket = assign(socket, :game, game)
{:reply, {:ok, %{"game" => game}}, socket}
end
Expand Down

0 comments on commit 1a65ffa

Please sign in to comment.