-
Notifications
You must be signed in to change notification settings - Fork 0
/
player_server.ex
71 lines (65 loc) · 1.52 KB
/
player_server.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
defmodule Generals.Game.PlayerServer do
def start_link(opts) do
Agent.start_link(fn -> map_user_ids_to_players(opts[:user_ids]) end)
end
@doc """
Return the user ids in the game
"""
def get_players(pid) do
Agent.get(pid, fn(state) ->
Map.keys(state)
end)
end
@doc """
Return the full mapping for the game
%{user_id => %{player_id:, left:}}
"""
def get_players_mapping(pid) do
Agent.get(pid, fn(state) ->
state
end)
end
@doc """
Return the player id for a user, if the user has not left the game
"""
def get_active_player_id(pid, user_id) do
Agent.get(pid, fn(state) ->
case Map.get(state, user_id) do
nil -> nil
%{left: true} -> nil
%{player_id: player_id, left: false} -> player_id
end
end)
end
@doc """
Mark a given user as having left a game
"""
def user_left(pid, user_id) do
Agent.get_and_update(pid, fn(state) ->
Map.get_and_update(state, user_id, fn(player_map) ->
case player_map do
nil -> :pop
player_map -> {player_map, Map.put(player_map, :left, true)}
end
end)
end)
|> case do
nil -> false
_ -> true
end
end
defp map_user_ids_to_players(user_ids) do
Enum.shuffle(user_ids)
|> Enum.with_index
|> Enum.map(fn({user_id, player_id}) ->
{
user_id,
%{
player_id: player_id,
left: false,
}
}
end)
|> Enum.into(%{})
end
end