-
Notifications
You must be signed in to change notification settings - Fork 2
/
player.ex
64 lines (49 loc) · 1.49 KB
/
player.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
defmodule GameManager.Player.Player do
alias TableManager.Table.{Dealer, Hand}
# Client Api
def add_player_info(player_id, info) do
GenServer.cast(player_id(player_id), {:add_info, info})
end
def get_info(player_id) do
GenServer.call(player_id(player_id), :get_info)
end
def hit(player_id) do
GenServer.call(player_id(player_id), :hit)
end
def stay(player_id) do
GenServer.call(player_id(player_id), :stay)
end
# GenServer Api
def start_link(player_id, table_id) do
GenServer.start_link(__MODULE__, table_id, [name: player_id(player_id)])
end
def init(table_id) do
{:ok, %{table_id: table_id, cards: []}}
end
def handle_call(:hit, _from, state) do
card = Dealer.hit(state.table_id)
new_cards = case Map.get(state, :cards) do
nil -> [card]
cards -> [card] ++ state.cards
end
hand = %Hand{cards: new_cards}
count = Hand.count(hand)
hit_info = %{
new_card: card,
hand_count: count,
hand: hand
}
{:reply, hit_info, %{state | cards: List.flatten(new_cards)}}
end
def handle_call(:stay, _from, state) do
{:reply, GameManager.Table.StateMachine.next_player(state.table_id), state}
end
def handle_call(:get_info, _from, state) do
{:reply, state, state}
end
def handle_cast({:add_info, info}, state) do
player_info = Map.put(state, :name, info[:name]) |> Map.put(:id, info[:id])
{:noreply, player_info}
end
defp player_id(player_id), do: :"player_#{player_id}"
end