aboutsummaryrefslogtreecommitdiff
path: root/tictactoe-2/apps/ttt_server/src/ttt_server.erl
diff options
context:
space:
mode:
Diffstat (limited to 'tictactoe-2/apps/ttt_server/src/ttt_server.erl')
-rw-r--r--tictactoe-2/apps/ttt_server/src/ttt_server.erl93
1 files changed, 93 insertions, 0 deletions
diff --git a/tictactoe-2/apps/ttt_server/src/ttt_server.erl b/tictactoe-2/apps/ttt_server/src/ttt_server.erl
new file mode 100644
index 0000000..62979e8
--- /dev/null
+++ b/tictactoe-2/apps/ttt_server/src/ttt_server.erl
@@ -0,0 +1,93 @@
+-module(ttt_server).
+
+-export([
+ start/0,
+ start_local/0,
+ stop/0,
+ stop/2,
+ loop/1,
+
+ start_game/1,
+ dump/1]).
+
+-import(ttt, [move/4, who_wins/1, format/1, empty_board/0]).
+
+-record(ttt_game, {
+ ref = make_ref(),
+ board,
+ player1,
+ player2}).
+
+-record(ttt_state, {
+ games = []}).
+
+-define(GLOBAL_NAME, ttt).
+
+loop(State) ->
+ _State =
+ receive
+ {Player1, start} when is_pid(Player1) ->
+ Board = ttt:empty_board(),
+ io:format("board:~n~s~n", [ttt:format(Board)]),
+ Game = #ttt_game{board = Board, player1 = Player1},
+ #ttt_state{games = [Game, State#ttt_state.games]},
+ Player1 ! {ok, Game#ttt_game.ref};
+ dump ->
+ io:format("Server state:~n~p~n", [State]),
+ State;
+ stop ->
+ io:format("Exiting~n", []),
+ exit(normal);
+ {stop, Pid} ->
+ Pid ! ok,
+ exit(normal);
+ X ->
+ io:format("unexpected message: ~p~n", [X]),
+ State
+ end,
+ case _State of
+ _ when _State =/= State ->
+ io:format("New State: ~p~n", [_State]);
+ _ -> _State
+ end,
+ ?MODULE:loop(_State).
+
+start_game(Server) ->
+ Server ! {self(), start},
+ receive
+ {ok, Game} ->
+ io:format("Game started: ~w~n", [Game]),
+ {ok, Game};
+ X ->
+ io:format("Game start failed: ~w~n", [X]),
+ X
+ after 100 ->
+ io:format("timeout~n", []),
+ {timeout}
+ end.
+
+dump(Server) ->
+ Server ! dump.
+
+start_local() ->
+ InitialState = #ttt_state{},
+ spawn(?MODULE, loop, [InitialState]).
+
+start() ->
+ Pid = start_local(),
+ case global:register_name(?GLOBAL_NAME, Pid) of
+ yes ->
+ io:format("Server started, pid=~p~n", [Pid]);
+ X ->
+ io:format("Register name failed: ~p~n", [X]),
+ Pid ! stop
+ end.
+
+stop(Server, Pid) ->
+ Server ! {stop, Pid}.
+
+stop() ->
+ case global:whereis_name(?GLOBAL_NAME) of
+ undefined -> io:format("Server not running~n");
+ Pid -> Pid ! {stop, self()}
+ end.