【问题标题】:Reading variable in prolog multible times多次读取序言中的变量
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • @Alexnder,但我遇到了另一个问题:两次读取相同的输入会给出 True,就像我输入两个零一样,它会给出真正的女巫会停止精确。
  • 我不确定我是否理解您的问题。您可以改写它并作为一个单独的问题发布吗?
猜你喜欢
  • 2015-07-16
  • 2023-01-26
  • 2017-01-24
  • 1970-01-01
  • 2023-03-11
  • 2022-12-31
  • 1970-01-01
  • 2022-09-29
  • 2013-12-01
相关资源
最近更新 更多