Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Guess My Number

% Guess My Number - Brandon Treno
% I left the module name as "helloworld" to make it easy to copy and paste 
% without needing to rename the .erl file
-module(helloworld).
-import(io, [put_chars/1]).
-export([guess_loop/2, main_loop/0, start/0]).

guess_loop(Attempts, MyNum) ->
    Guess = element(2,io:fread("", "~d")),
    
    io:fwrite("Debug: ~w", [MyNum]),
    
    io:fwrite("~nDebug- ~w", Guess),
    
    io:fwrite("~nDebug: ~w", [Attempts]),
    % compare guess
    if
        Guess == [MyNum] ->
            io:fwrite("~nCorrect!"),
            ok;
        true -> 
            if
                Guess > [MyNum] ->
                    io:fwrite("~n<Too high> ");
                true ->
                    io:fwrite("~n<Too low>")
            end
    end,
    
    if
        [Attempts] > [5] ->
            io:fwrite("~nThe answer was ~w...~n", [MyNum]);
        true ->
            put_chars("h"),
            Attempts = Attempts + 1,
            guess_loop(Attempts, MyNum)
            
    end.

main_loop() ->
    % Intro
    put_chars("\nCan You Guess My Number? (1-100)"),
    put_chars("\n================================\n\n"),
    
    % Main loop
    MyNum = rand:uniform(100),
    % Guess Loop
    guess_loop(1, MyNum),
    
    Response = io:fread("\nWould you like to play again?  ", "~s"),
    if
        % the {ok, []} is the best workaround I could find
        % for how erlang handles strings and input
        (Response == {ok, ["yes"]}) or (Response == {ok, ["y"]}) or (Response == {ok, ["1"]}) ->
            main_loop();
        true ->
            put_chars("")
    end.
    

start() ->
    main_loop().

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.