43:a8365c989b1c
Anton Shestakov <engored@ya.ru>, Thu, 06 Mar 2014 19:38:46 +0900
Get win stats by nicknames, not pids.

next change 44:8d400faca258
previous change 42:82a465d8a5c1

src/rps.erl

Permissions: -rw-r--r--

Other formats: Feeds:
-module(rps).
-export([
go/0,
lobby/0, counter/0, printer/0]).
-define(BOTS, [fool, copycat, gambler]).
-define(RULES, rps5).
go() ->
rps_nickserv:start_link(),
rps3:start_link(),
rps5:start_link(),
register(lobby, spawn_link(?MODULE, lobby, [])),
register(counter, spawn_link(?MODULE, counter, [])),
register(printer, spawn_link(?MODULE, printer, [])),
[spawn_link(rps_bots, Bot, []) || Bot <- ?BOTS].
lobby() ->
lobby([]).
lobby(Players) when length(Players) =:= length(?BOTS) ->
Room = spawn_link(rps_room, room, [?RULES, Players]),
lists:foreach(fun(Player) -> Player ! {room, Room, ?RULES} end, Players),
lobby([]);
lobby(Players) ->
receive
{join, Who} ->
lobby([Who|Players])
end.
counter() ->
counter(0, 0, dict:new(), dict:new()).
counter(Plays, Draws, Wins, Hands) ->
receive
{draw, _} ->
counter(Plays + 1, Draws + 1, Wins, Hands);
{winner, {Hand, Winner}} ->
counter(Plays + 1, Draws,
dict:update_counter(Winner, 1, Wins),
dict:update_counter(Hand, 1, Hands));
{sendstats, Pid} ->
Format = fun({Who, W}) -> {rps_nickserv:whois(Who), W} end,
WinsByNickname = lists:map(Format, dict:to_list(Wins)),
Pid ! {stats, {
plays, Plays,
draws, Draws,
wins, WinsByNickname,
hands, dict:to_list(Hands)}},
counter(Plays, Draws, Wins, Hands)
end.
printer() ->
receive
{stats, Stats} ->
io:format("Stats: ~w.~n", [Stats])
after 1000 ->
counter ! {sendstats, self()}
end,
printer().