1

我想用prolog(连接四)写一个简单的游戏。我想多次读取用户的输入,输入是列号。当我第二次阅读“Col”并输入不同的值时,它会崩溃并给出错误(我知道如何多次阅读):

:- dynamic state/3.
:- dynamic top/2.

%% the problem is in the read here
play(Color, Col) :-
top(Col, Raw) -> addRing(Col, Raw, Color); (assert(top(Col,0)) ,addRing(Col, 0, Color)),
win(X,Y,Winner)
-> (write('Game over, winner is '),write(Winner));
(write('Your turn, column? '), read(Col), write('read column is '), write_ln(Col), play(red,Col)).

addRing(Col, Raw, Color):-
assert(state(Col,Raw,Color)),
Next is Raw + 1, retract(top(Col, Raw)), assert(top(Col, Next)).
win(X,Y, Winner) :-
state(X,Y, Color), N1 is X - 1, state(N1, Y, Color), N2 is N1 - 1, state(N2, Y, Color), N3 is N2 - 1, state(N3, Y, Color), Winner = Color.

%% the reset is some methods to determine the winner
win(X,Y, Winner) :-
state(X,Y, Color), N1 is Y - 1, state(X, N1, Color), N2 is N1 - 1, state(X,N2, Color), N3 is N2 - 1, state(X, N3, Color), Winner = Color.

win(X,Y, Winner) :-
state(X,Y, Color),
N1 is X + 1, M1 is Y + 1, state(N1, M1, Color),
N2 is N1 + 1, M2 is M1 + 1, state(N2, M2, Color),
N3 is N2 + 1, M3 is M2 + 1, state(N3, M3, Color),
Winner = Color.

win(X,Y, Winner) :-
state(X,Y, Color),
N1 is X + 1, M1 is Y - 1, state(N1, M1, Color),
N2 is N1 + 1, M2 is M1 - 1, state(N2, M2, Color),
N3 is N2 + 1, M3 is M2 - 1, state(N3, M3, Color),
Winner = Color.

例如,要测试游戏,您可以通过调用来启动它play(Red,0),然后它会询问列号。

4

1 回答 1

1

我认为Col在递归调用中应该是Col1,即与头部不同的变量。

于 2012-05-20T16:34:06.210 回答