A simple guessing game in Erlang

Recently, I found out about a book called Inventing your own computer games with Python.  In it, there's a "Guess the Number" game.  Man, it takes me back to when I was toying around in GW-Basic.  I've been meaning to do Erlang again, and was going through Learn You Some Erlang for Greater Good, when I wanted a simple project to practice some Erlangian.  I had forgotten a lot of the basics, and this was a good way to get back into it.  Not a very fun game to play–maybe I'll try Bagels later on.  For now, it's just "Guess the Number".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
-module(guess).
-export([start/0]).

start() ->
    intro(6).

intro(Guesses) ->
    io:format("Welcome to the Guessing game!n"),
    io:format("I'm thinking of a number between 1 and 20n"),
    get_guess(Guesses, random:uniform(20)).

get_guess(Guesses, Secret) when Guesses =< 0 ->
    lose_game(Secret);
get_guess(Guesses, Secret) ->
    io:format("You have ~p guesses left.n", [Guesses]),
    {_, User_guess} = io:read("What is your guess (end with .)? "),
    check_guess(Guesses, User_guess, Secret).

check_guess(_, User_guess, Secret) when User_guess =:= Secret ->
    win_game(Secret);
check_guess(Guesses, User_guess, Secret) when User_guess >= Secret ->
    io:format("The number I'm thinking of is lower. Try again!n"),
    get_guess(Guesses - 1, Secret);
check_guess(Guesses, User_guess, Secret) when User_guess =< Secret ->
    io:format("The number I'm thinking of is higher. Try again!n"),
    get_guess(Guesses - 1, Secret).

lose_game(Secret) ->
    io:format("You lost the game!n"),
    io:format("The number was ~pn", [Secret]).

win_game(Secret) ->
    io:format("You win the game! 🙂n"),
    io:format("The number was ~pn", [Secret]).

What's interesting is that basic process and components of the game map very well to each decision that must be made, so you don't need to use an if statement at all.  All you need are the guards for each function.  Also, the entire game state needs to be carried in the parameters of each function.  I can see how that can be a pain for more complex games.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s