From 1a65ffab6e26bf048ab40406547fadc6c671f867 Mon Sep 17 00:00:00 2001 From: William Guo Date: Mon, 12 Feb 2018 23:41:05 -0500 Subject: [PATCH] Make save game and backup game --- lib/memory/application.ex | 1 + lib/memory/game_backup.ex | 19 +++++++++++++++++++ lib/memory_web/channels/games_channel.ex | 3 ++- 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 lib/memory/game_backup.ex diff --git a/lib/memory/application.ex b/lib/memory/application.ex index 6ff636c6..25b069e1 100644 --- a/lib/memory/application.ex +++ b/lib/memory/application.ex @@ -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 diff --git a/lib/memory/game_backup.ex b/lib/memory/game_backup.ex new file mode 100644 index 00000000..2a102884 --- /dev/null +++ b/lib/memory/game_backup.ex @@ -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 diff --git a/lib/memory_web/channels/games_channel.ex b/lib/memory_web/channels/games_channel.ex index 52cf46dc..9cdeb996 100644 --- a/lib/memory_web/channels/games_channel.ex +++ b/lib/memory_web/channels/games_channel.ex @@ -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 @@ -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