Reputation: 442
I am trying to create a "Who Is It" game (person guessing part).
I would like to check if user input equals the value/person that is saved in a predicate. Based on this, I would then return to the user if the value/person has been guessed or not.
The random person is chosen from a list called characters
each time the menu is retuned to the user interface.
Which library do I need to use, or how would I achieve this kind of evaluation?
:- dynamic xxxxxxxxxxxx/1.
%characteristics of a person/character
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
male(bill).
male(alfred).
female(claire).
female(anne).
bald(bill).
beard(bill).
beard(alfred).
blushes(bill).
redshirt(alfred).
hat(claire).
blond(claire).
dress(anne).
earrings(anne).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
chosen_character(_).
menu :-
write('Possible characters to choose from:'),nl,
characters(L), write(L),nl,
read(Input),
%CODE THAT COMPARES INPUT TO 'chosen_character' AND RETURNS NAME IF CORRECT ELSE GUESS AGAIN.
menu.
character(L) :- findall(X, (male(X) ; female(X)), L).
new_character(Ans):-
characters(L),
length(L, X),
R is random(X),
N is R+1,
random_between(L, N, Ans),
chosen_character(Ans).
random_between([H|T],1,H).
random_between([H|T],N,E):-
N1 is N-1,
random_between(T,N1,E1),
E=E1.
Upvotes: 0
Views: 301
Reputation: 5509
Assuming you already have a list of names that can be chosen (defined by the predicate characters/1
) and that you're using SWI-Prolog (since the question was originally tagged with swi-prolog
), a possible solution is as follows:
characters([bill, alfred, claire, anne]).
guess :-
characters(Names),
random_member(Name, Names),
guess(Name).
guess(Name) :-
characters(Names),
format(atom(Prompt), '\nChoose one of ~w: ', [Names]),
prompt1(Prompt),
read_line_to_string(user_input, String),
atom_string(Atom, String),
( Atom = Name
-> format('Your guess is correct!\n')
; format('Your guess is incorrect!\n'),
guess(Name) ).
Note that SWI-Prolog already has some built-in predicates which are very useful for this application (random_member/2, format/3, prompt1/1, read_line_to_string/2, and atom_string/2).
Running example:
?- guess.
Choose one of [bill,alfred,claire,anne]: anne
Your guess is incorrect!
Choose one of [bill,alfred,claire,anne]: bill
Your guess is incorrect!
Choose one of [bill,alfred,claire,anne]: claire
Your guess is correct!
true.
Upvotes: 1