Prolog从列表中找到相应的元素

时间:2018-02-27 13:49:57

标签: list prolog

tennis([court, singles, doubles, outdoor, ball, racket]).
games([tennis, diving, soccer]). /* A list of games */
game_detail(tennis, [[court, 'two for doubles'], [singles, 'one for singles']]).

我正在制作一个游戏,prolog程序回答提问者的问题。 首先,我向提问者提供所有可用选项的列表,提问者可以询问带有查询的程序(X)。

我为每场比赛做了选择(奥运会为Q& A比赛)。 但是,如何让程序回答相应选项的详细信息? 在这里,第二个元素(字符串)在另一个列表的列表中。

感谢您的帮助。

到目前为止我写的整个代码如下。

/* Game database */
tennis([court, singles, doubles, outdoor, ball, racket]).
diving([pool, singles, jump]).
soccer([ball, number, field]).
basketball([ball, number, field, foul]).
baseball([ball, number, field]).
fencing([number, field, foul]).
games([tennis, diving, soccer]). /* A list of games */
game_detail(tennis, [[court, 'two for doubles'], [singles, 'one for singles']]).
game_detail(diving, [[pool, '50m pool'], [singles, 'one swims 50m']]).
game_detail(soccer, [[ball, 'designated ball'], [number, '11 players']]).

/* Calling the corresponding answer for valid options */
detail(Game,[Option|Rest]).
detail(X,Y) :- game_detail(X,Options) .
Options = [[court, 'two'], [singles, 'one for']].

/* Random game selection */
rand(X) :- games(Y), random_member(X,Y), assert(selected(X)).
:- dynamic selected/1.
game_init :-
    retract(selected(Y)),
    retract(all_options(Z)),
    all_options.

/* Counter */
:- dynamic counter/1.
counter(0). /* Initialize counter as 0 */
increment :-  /* Set counter increment as 1 */
    retract(counter(C)),
    succ(C, C1),
    assertz(counter(C1)).
cnt_init :-  /* Initialize counter as 0 for next game */
    retract(counter(C)),
    assertz(counter(0)).

/* Showing all options of randomly selected game */
:- dynamic all_options/1.
all_options :- rand(X), call(X,Z), write(Z), assert(all_options(Z)).

/* Pop up the option from questioner */
delMember(_, [], []).
delMember(X, [X|Xs], Y) :-
    delMember(X, Xs, Y).
delMember(X, [T|Xs], [T|Y]) :-
    dif(X, T),
    delMember(X, Xs, Y).


/* Answering has(X) query */
has(X) :- counter(C), all_options(Y),
    (   C=10 ->
    write('Guess the game')
    ;   C<10, member(X,Y) ->
    write('Yes'), increment,
        delMember(X,Y,Z),
        retract(all_options(Y)), assert(all_options(Z))
    ;   C<10, not(member(X,Y)) ->
    write('No'), increment
    ;   write('Invalid options')).

/* Answering is(X) query */
is(X) :- selected(Y), counter(C),
    (X=Y  ->
    write('successful guess'), cnt_init, game_init
    ;   C=10, not(X=Y) ->
    write('unsuccessful guess'), cnt_init, game_init
    ;   C<10, not(X=Y) ->
    write('unsuccessful guess'), increment
    ).


/* Initialize program settings */
:- initialization(all_options).

0 个答案:

没有答案