Jeff
Jeff

Reputation: 353

Number guessing game in Prolog

I am trying to build a simple program where the user has 3 tries to guess a number but there is a compilation error and I don't know where the problem is.

actual_number(500).
actual_number(Num).
start:-
write('Enter your first guess'), nl,
read(Guess1),
Guess1 =\= Num -> write('Wrong you have 2 tries left'),
read(Guess2);
Guess1 == Num -> write('Correct'),!.
Guess2 =\= Num -> write('Wrong you have 1 try left'),
read(Guess3);
Guess2  == Num -> write('Correct'),!.
Guess3 =\= Num -> write('Wrong the number was 500'),!;
Guess3 == Num -> write('Correct').

Upvotes: 2

Views: 645

Answers (1)

Duda
Duda

Reputation: 3746

I use Swish to test the code. The main difference from the following first code snipped is that the following version is more structured and not using cuts. Cuts are not necessary since you are using If-the-else directives which use cuts by themselves. Please note that the disjunction (;) of calls has a different priority than the conjunction (,). Use brackets to define the scope of the disjunction as well as the statesments which have to be true for the if-then-else to fire.

actual_number(500).

start:-
    actual_number(Num),
    write('Enter your first guess'), nl,
    read(Guess1),
    (   Guess1 == Num 
    ->  write('Correct')
    ;   write('Wrong you have 2 tries left'), nl,
        read(Guess2),
        (   Guess2 == Num 
            ->  write('Correct')
        ;   write('Wrong you have 1 try left'), nl,
            read(Guess3),
            (   Guess3 == Num 
            ->  write('Correct')
            ;   write('Wrong the number was '),
                write(Num)
            )
        )
    ).

A second approach counts the number of tries and does in principle the same, just the code is more prolog-ish.

actual_number(500).

start:-
    write('Enter your first guess'), nl,
    start(3).

start(N):-
    N>0,
    actual_number(Num),
    read(Guess),
    (   Guess == Num
    ->  write('Correct')
    ;   Nnew is N-1,
        write('Wrong you have '),
        write(Nnew), 
        write(' tries left'), nl,
        start(Nnew)
    ).
    
start(0):-
    actual_number(Num),
    write('Wrong the number was '),
    write(Num).
    
    

Upvotes: 1

Related Questions