prolog学习--1. 寻找Nani游戏

本文介绍了一款基于Prolog的Nani寻物游戏,详细解释了游戏中的房间布局、物品位置及玩家如何在游戏中移动和查找物品。通过定义房间、物品位置、连接房间的门以及物品属性,玩家可以在厨房、办公室等房间内寻找苹果、手电筒等物品,并了解哪些物品是可以食用的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、寻找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).

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值