【发布时间】:2021-09-19 22:45:18
【问题描述】:
我想用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) 来启动它,然后它会询问列号。
【问题讨论】:
-
我测试了你的代码,但你想要它做什么不是很清楚。 play(Red, 0) 输入数字后结束,然后呢?
-
@Junuxx,读完后有一个分号,它应该继续要求你再玩一回合,当你输入0以外的列时,它会崩溃(0是值保存在“Col”中,这就是问题所在)我需要它来读取用户的不同输入。
标签: prolog