Right or wrong (v1)

The next step is for the server to tell the clients whether or not their guesses are right or wrong.

game_server_v1/1

In the file game.erl you find the following function declaration with an updated version of previous game server loop.

 1game_loop_v1(Secret) ->
 2    receive
 3        {request, {guess, Secret}, From} ->
 4            From ! {reply, {right, Secret}},
 5            game_loop_v1(Secret);
 6        {request, {guess, N}, From} ->
 7            From ! {reply, {wrong, N}},
 8            game_loop_v1(Secret);
 9        {request, version, From} ->
10            From ! {reply, {version, v1}},
11            game_loop_v1(Secret)
12    end.

Note the first receive pattern {request, {guess, Secret}, From} and how the variable Secret is used both as the argument to the server loop and in this pattern. When you create a game server, the variable Secret is bound to the value you provide as argument to game_loop_v1/1, hence the pattern {request, {guess, Secret}, From} will only match a correct guess.

An alternative is to use a guarded pattern to detect correct guesses.

{request, {guess, N}, From} when N == Secret -> 
    From ! {reply, {right, Secret}}, 
    game_loop_v1(Secret);

For each incoming message, the receive patterns are tried from top to bottom until a match is found. Therefore the second receive pattern {request, {guess, N}, From} will only match incorrect guesses since correct guesses have already been matched by the first pattern.

The third and last receive pattern makes it possible for clients to ask for the server version. Here we simply replies with the tuple {reply, {version, v1}} to such a request.

start/2

In the beginning of game.erl you find the following function declaration

start(v1, Secret) ->
    spawn(?MODULE, game_loop_v1, [Secret]);

Using this functions makes is easy to spawn a new server from the Erlang shell.

6> S1 = game:start(v1, 55).
<0.62.0>
7> 

guess/2

In game.erl you also find the following function which makes it easy to sent a guess request to the server and wait for the reply.

1guess(Server, N) ->
2    Server ! {request, {guess, N}, self()},
3    receive
4        {reply, Reply} -> Reply
5    end.

We can now try and send requests to the server and see the replies.

7> game:guess(S1, 17).
{wrong,17}
6> game:guess(S1, 55). 
{right,55}
8> 

version/1

There is also a function for asking the server for the version.

8> game:version(S1).
v1
9>