45:0bbe9c057774
Anton Shestakov <engored@ya.ru>, Sat, 08 Mar 2014 15:36:49 +0900
Now lobby waits for other players to join or starts without them. Before it waited for a fixed number of players.

next change 46:1514111fb94a
previous change 44:8d400faca258

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).
-define(TIMETOJOIN, 10).
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([], ?TIMETOJOIN).
lobby(Players, 0) ->
Room = spawn_link(rps_room, room, [?RULES, Players]),
lists:foreach(fun(Player) -> Player ! {room, Room, ?RULES} end, Players),
lobby();
lobby(Players, Timeout) ->
Wait = case length(Players) of
0 -> infinity;
_ -> 1000
end,
receive
{join, Who} ->
lobby([Who|Players], Timeout)
after
Wait ->
io:format("~w players joined, waiting ~w", [length(Players), Timeout]),
lobby(Players, Timeout - 1)
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} ->
{plays, Plays, draws, Draws, wins, Wins, hands, Hands} = Stats,
io:format("Plays: ~w, draws: ~w, wins: ~p, hands: ~w.~n",
[Plays, Draws, Wins, Hands])
after 1000 ->
counter ! {sendstats, self()}
end,
printer().