How to resolve the algorithm Guess the number/With feedback step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Guess the number/With feedback step by step in the Prolog programming language

Table of Contents

Problem Statement

Write a game (computer program) that follows the following rules:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Guess the number/With feedback step by step in the Prolog programming language

Source code in the prolog programming language

main :-
    play_guess_number.


/* Parameteres */

low(1).
high(10).


/* Basic Game Logic */

play_guess_number :-
    low(Low),
    high(High),
    random(Low, High, N),
    tell_range(Low, High),
    repeat,                         % roughly, "repeat ... (until) Guess == N "
        ask_for_guess(Guess),
        give_feedback(N, Guess),
    Guess == N.

/* IO Stuff */

tell_range(Low, High) :-
    format('Guess an integer between ~d and ~d.~n', [Low,High]).

ask_for_guess(Guess) :-
    format('Guess the number: '),
    read(Guess).

give_feedback(N, Guess) :-
    ( \+integer(Guess) -> writeln('Invalid input.')
    ; Guess < N        -> writeln('Your guess is too low.')
    ; Guess > N        -> writeln('Your guess is too high.')
    ; Guess =:= N      -> writeln("Correct!")
    ).


?- main.
Guess an integer between 1 and 10.
Guess the number: a.
Invalid input.
Guess the number: 3.
Your guess is too low.


  

You may also check:How to resolve the algorithm Number reversal game step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Arithmetic-geometric mean step by step in the Stata programming language
You may also check:How to resolve the algorithm Sum of a series step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Real constants and functions step by step in the C programming language
You may also check:How to resolve the algorithm Minimum multiple of m where digital sum equals m step by step in the Pascal programming language