1

我正在尝试在 Prolog 中编写一个简单的 Noughts-and-Crosses (Tic-tac-Toe) 评估器。我要做的第一件事是让程序计算所有可能的获胜板。逻辑还不完整——它不检查可能由实际玩游戏产生的有效棋盘——它只是在寻找任何“3 行”。

问题是,程序 'stops-short' :它正确检测到第 3 行并统一构成第 3 行的变量 - 但不显示其他变量的组合。(不位于获胜线上的单元格)。

这是我的程序和示例输出:

/*
Attempting to create a program that will output 'x' ,'o' or 'none'
given a (filled-in) tic-tac-toe board.
'x' - 'x' has won. (Literally there is a line of x's)
'o' - 'o' as above
'none' : no winners on the given board.

This does NOT check whether the board is in a valid state for tic-tac-toe!
*/

/* Define board states as facts */
cell(none).
cell(x).
cell(o).

/* Define winning line of 3 */
win_line(C1, C2, C3, Winner) :-
        cell(C1),
        cell(C2),
        cell(C3),
        C1 \== none,
        C1==C2,
        C2==C3,
        Winner=C1.

/* define the board rule: variables are 'encoded' for each cell by a coordinate (col,row) */
board(  C11, C12, C13,
        C21, C22, C23,
        C31, C32, C34, Winner) :-
        win_line(C11, C12, C13, Winner); /* Test the three rows */
        win_line(C21, C22, C23, Winner);
        win_line(C31, C32, C33, Winner);
        win_line(C11, C21, C31, Winner); /* Test the three columns */
        win_line(C12, C22, C32, Winner);
        win_line(C13, C23, C34, Winner);
        win_line(C13, C23, C34, Winner); /* Test the two diaganols */
        win_line(C11, C22, C34, Winner);
        win_line(C13, C22, C31, Winner).

我的查询,输出如下:

| ?- board(C11,C12,C13, C21,C22,C23, C31,C32,C33, o).     

C11 = o
C12 = o
C13 = o ? a

C21 = o
C22 = o
C23 = o

C31 = o
C32 = o

C11 = o
C21 = o
C31 = o

C12 = o
C22 = o
C32 = o

C13 = o
C23 = o
C33 = o

C13 = o
C23 = o
C33 = o

C11 = o
C22 = o
C33 = o

C13 = o
C22 = o
C31 = o

(4 ms) yes

版本信息:

GNU Prolog 1.3.0
By Daniel Diaz
Copyright (C) 1999-2007 Daniel Diaz
| ?- 
4

2 回答 2

1

我看到你已经解决了你的第一个问题。

获取查询的所有可能结果的一种方法是使用findall/3

?- findall([A,B,C,D,E,F,G,H,I], board(A,B,C,D,E,F,G,H,I,o), Results).
Results = [[o,o,o,_,_,_,_,_,_],
           [_,_,_,o,o,o,_,_,_],
           [_,_,_,_,_,_,o,o,o],
           [o,_,_,o,_,_,o,_,_],
           [_,o,_,_,o,_,_,o,_],
           [_,_,o,_,_,o,_,_,o],
           [_,_,o,_,_,o,_,_,o],
           [o,_,_,_,o,_,_,_,o],
           [_,_,o,_,o,_,o,_,_]]

请注意,它只考虑在这种情况下实际重要的值,而忽略其他值。

如果您需要将其他值锁定到实际原子,有一些方法可以做到这一点,尽管它涉及编写另外几个谓词来查找所有可能的值组合以获得结果,对于Results.

于 2013-06-01T19:04:30.987 回答
0

明白了,我想 - 我已经像这样改变了董事会规则:

/* define the board rule: variables are 'encoded' for each cell by a coordinate (col,row) */
board(  C11, C12, C13,
        C21, C22, C23,
        C31, C32, C34, Winner) :-
        cell(C11), cell(C12), cell(C13),
        cell(C21), cell(C22), cell(C23),
        cell(C31), cell(C32), cell(C33),
        win_line(C11, C12, C13, Winner); /* Test the three rows */
[...]as before

所以添加进一步的子句,每个变量都与一个单元格事实相结合......不是 100% 确定我为什么需要这样做......但它似乎工作......

于 2013-06-01T18:44:39.843 回答