--- a/src/rps.erl Mon Mar 03 15:42:17 2014 +0900
+++ b/src/rps.erl Mon Mar 03 19:46:02 2014 +0900
lobby/0, counter/0, printer/0]).
-define(BOTS, [fool, copycat, gambler]).
rps_nickserv:start_link(),
register(lobby, spawn_link(?MODULE, lobby, [])),
register(counter, spawn_link(?MODULE, counter, [])),
register(printer, spawn_link(?MODULE, printer, [])),
--- a/src/rps3.erl Mon Mar 03 15:42:17 2014 +0900
+++ b/src/rps3.erl Mon Mar 03 19:46:02 2014 +0900
--export([get_hands/0, winning_hand/1]).
+-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
+-export([start_link/0, get_hands/0, winning_hand/1, why/2]).
-get_hands() -> [rock, paper, scissors].
+-record(state, {hands=[], beats=dict:new(), loses=dict:new(), why=dict:new()}).
+ gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
+parse_rules([V1,Label,V2|T], #state{hands=Hands, beats=Beats, loses=Loses, why=Why}) ->
+ beats=dict:append(V1, V2, Beats),
+ loses=dict:append(V2, V1, Loses),
+ why=dict:store({V1, V2}, Label, Why)},
+ parse_rules([V2|T], Acc);
+parse_rules([_V2], Acc) ->
- beats(H, lists:reverse(get_hands())).
+ Text = "scissors cut paper covers rock crushes scissors",
+ Tokens = lists:map(fun list_to_atom/1, string:tokens(Text, " ")),
+ {ok, parse_rules(Tokens, #state{})}.
+handle_call(get_hands, _From, State=#state{hands=Hands}) ->
% rock, rock, rock -> rock
% rock, paper, paper -> paper
% rock, rock, paper -> paper
+handle_call({winning_hand, Hands}, _From, State) ->
HSet = sets:from_list(Hands),
- case sets:is_element(loses(Hand), HSet) of
+ Loses = dict:fetch(Hand, State#state.loses),
+ case sets:is_disjoint(sets:from_list(Loses), HSet) of
+handle_call({why, H1, H2}, _From, State=#state{why=Why}) ->
+ {reply, dict:fetch({H1, H2}, Why), State}.
+handle_cast(_Msg, State) -> {noreply, State}.
+handle_info(_Msg, State) -> {noreply, State}.
+terminate(_Reason, _State) -> ok.
+code_change(_OldVersion, State, _Extra) -> {ok, State}.
+ gen_server:call(?MODULE, get_hands).
+ gen_server:call(?MODULE, {winning_hand, Hands}).
+ gen_server:call(?MODULE, {why, H1, H2}).