1

プロローグ(Connect four)で簡単なゲームを書きたい。ユーザーからの入力を何度も読みたいのですが、入力は列番号です。'Col' を 2 回目に読んで別の値を入力すると、クラッシュして false になります (何度も読む方法を知っています)。

:- 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 に答える