成功的prolog查询没有显示真实

时间:2014-06-14 12:57:51

标签: prolog

测试一些Prolog代码,看看当白色(w)从电路板的一侧到另一侧有连接路径时是否可以显示游戏结果。 到目前为止,我遇到的最大问题是gameover/2确实通过了每一侧的所有节点,并检查它们连接后是否停止或显示它们是什么时候。因此,在测试此查询时:

gameover([[e,e,b,e,e],[e,w,w,b,e],[b,w,b,w,w],[w,w,b,b,b],[e,e,b,w,e]], w). 

Prolog在应该是真的时返回no。我已经完成了我能做的一切,但我是Prolog的新手,我确信我一定会错过一些明显的东西。

gameover(State, w) :-
    width(State, W), write(W), nl,
    series(1, W, NewList), write(NewList), nl,
    member(X1, NewList), write(X1), nl,
    write(loc(X1,1)), nl, write('X1'), nl,
    member(X2, NewList), write(X2), nl,
    write(loc(X2,W)), nl, write('X2'), nl,
    connected(State, loc(X1,1), loc(X2,W), w).

我已经非常彻底地测试了连接,成员,系列和宽度,并确信它们都能正常工作,所以我认为它必须是我在上面的代码中所做的事情。 gameover(State,b)使用Y坐标而不是X也有类似的谓词。它也有同样的麻烦。

连接:

connected(State, Start, End, Colour) :- get_location(State, End, Colour),
                                        get_location(State, Start, Colour),
                                        connects(State, End, Colour, Start, [Start]).

connected(_State, _Next, _Colour, End, Close):- member(End, Close).

%checking to make sure every node is connected to the other using linked
%list of children from linked- check child is not member of closed list(meaning it has been checked before)
%get location of child to check for colour
%recursive call, include children in closed list to mark they have been checked and won't be checked again                                      
connects(State, End, Colour, Next, Close) :-  linked(Next, Child),
                                                \+member(Child, Close),
                                                get_location(State, Child, Colour),
                                                connects(State, End, Colour, Child, [Child|Close]).

connects(_State, End, _Colour, End, _Close).

1 个答案:

答案 0 :(得分:0)

通过适当的简化,并删除过度显示的中间计算,这里有一个可以帮助你的草图

gameover(State, Colour) :-
    width(State, W),
    get_location(State, loc(X1,1), Colour),
    connected(State, loc(X1,1), loc(_,W), w).

connected(State, L1, L2, Colour) :-
    connected_(State, [L1], L2, Colour).

connected_(_State, [Target|_], Target, _Colour).
connected_(State, [Last|Visited], Target, Colour) :-
    linked(Last,Link),
    get_location(State, Link, Colour),
    \+ memberchk(Link, Visited),
    connected_(State, [Link,Last|Visited], Target, Colour).

它是服务谓词connected_的关键字,它包含已访问的位置列表而不是起始位置,然后启用简单的深度优先访问。一个小测试,具有愚蠢的拓扑

width(_State, 3).

linked(loc(X,Y),loc(U,V)) :- (U is X+1 ; U is X-1), Y=V.
linked(loc(X,Y),loc(U,V)) :- (V is Y+1 ; V is Y-1), X=U.

get_location(State, loc(X,Y), Colour) :-
    nth(Y,State,Row), nth(X,Row,Colour).

?- S = [[e,w,e],[e,w,e],[e,w,e]], gameover(S,w).
S = [[e, w, e], [e, w, e], [e, w, e]] 
.

?- S = [[w,e,e],[e,w,e],[e,w,e]], gameover(S,w).
false.