prolog学习"/>
prolog学习
一、寻找Nani游戏
数据库如下:
room(kitchen).room(office).room(hall). room('dining room').room(cellar). door(office, hall).door(kitchen, office).door(hall, 'dining room').door(kitchen, cellar).door('dining room', kitchen).location(desk, office).location(apple, kitchen). location(flashlight, desk). location('washing machine', cellar).location(nani, 'washing machine').location(broccoli, kitchen).location(crackers, kitchen).location(computer, office).edible(apple).edible(crackers).tastes_yucky(broccoli).here(kitchen).
第一个问题是:office在本游戏中是不是一个房间。
?-room(office).
true.
Prolog回答yes,因为它在数据库中找到了room(office).这个事实。我们继续问:有没有attic这个房间。
?-room(attic).
false.
Prolog回答no,因为它在数据库中找不到room(attic).这个事实。同样我们还可以进行如下的询问。
?- location(apple, kitchen).
true.
?- location(kitchen, apple).
false.
二、代码
% 定义房间
room(kitchen).
room(office).
room(hall).
room('dining room').
room(celler).
% 定义物品位置
:- dynamic location/2.
location(desk,office).
location(apple,kitchen).
location(flashlight,desk).
location('washing machine',celler).
location(nani,'washing machine').
location(broccoli,kitchen).
location(crachers,kitchen).
location(computer,office).
% 定义从当前房间可以去哪个房间
door(office,hall).
door(kitchen,office).
door(hall,'dining room').
door(kitchen,celler).
door('dining room',kitchen).
% 定义物品是否可以食用
edible(apple).
edible(crachers).
tastes_yucky(broccoli).turned_off(flashlight).
% 定义初始位置
:- dynamic here/1.
here(kitchen).
% 查找食品位置
where_food(X,Y):- location(X,Y),edible(X).
% 当前房间可以到达的下一个房间
connect(X,Y):- door(X,Y).
connect(X,Y):- door(Y,X).
% 列出当前房间物品
list_things(Place):- location(X,Place),tab(2),write(X),nl,fail.
list_things(_).
% 列出当前房间可以到达的下一个房间
list_connections(Place):- connect(Place,X),tab(2),write(X),nl,fail.
list_connections(_).
% 查看当前房间物品和当前房间可以到达的下一个房间
look:- here(Place),write('You are int the '),write(Place),nl,write('You can see:'),nl,list_things(Place),write('You can go to:'),nl,list_connections(Place).
% 查看当前房间是否可以到达指定房间
can_go(Place):- here(X),connect(X,Place).
can_go(_):- write('You can not get there from here.'),nl,fail.
% 移动当前位置到下一个房间
move(Place):- retract(here(_)),asserta(here(Place)).
%到下一个房间
goto(Place):- can_go(Place),move(Place),look.can_take(Thing):- here(Place),location(Thing,Place).
can_take(Thing):- write('There is no '),write(Thing),write(' here.'),nl,fail.
take_object(X):- retract(location(X,_)),asserta(have(X)),write('taken'),nl.
take(X):- can_take(X),take_object(X).
更多推荐
prolog学习
发布评论