Prolog:连续更改两个已知值之间的变量 [英] Prolog: Changing a variable between two known values consecutivly

查看:47
本文介绍了Prolog:连续更改两个已知值之间的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Prolog 中创建游戏.在这个游戏中有两个玩家(玩家 w - 白色和 b-黑色).所以,我的目标是每次玩家结束时调用谓词 change_player 轮到玩.变量 C 将具有将要玩的玩家的值.玩家进行的游戏的谓词是 play(C).我还没有为 play 谓词创建代码,但我知道最终它会调用谓词 change_player(C).

I am trying to create a game in Prolog. In this game there are two players (player w - white and b-black). So, my objective is to call the predicate change_player each time a player ends is turn to play. The variable C will have the value of the player that will play. The predicate for the play made by a player is play(C). I have not created the code for the play predicate but I know that in the in the end it will call the predicate change_player(C).

我正在尝试这样做:

play(C):-
          ( code of the play)

          change_player(C).

change_player(C):- C=w -> (C = b, write(C)); %if the player is w change it to b and write value of C
                  (C = w, write(C)). %else change it to w and write value of C

但是当我执行 change_player(w) 时,它给了我一个错误.

But when I do change_player(w) it gives me an error.

你能告诉我我做错了什么吗?谢谢你

Can you tell me what Im doing wrong? Thankyou

推荐答案

您不能在 Prolog 中重新分配"变量.

You can't 'reassign' a variable in Prolog.

变量可以是自由的(即未指定的)或绑定到特定值(可以是另一个变量,自由或绑定并不重要).

A variable can be either free (i.e. unspecified) or bound to a specific value (that could be another variable, free or bound isn't important).

那么你必须重新考虑你的主循环",并添加另一个变量来绑定:

Then you must rethink you 'main loop', and add another variable to bind:

play(CurrPlayer, NextPlayer) :-
  % play it
  change_player(CurrPlayer, NextPlayer).

change_player(C, N) :-
   (  C = w
   -> N = b     % if the player is w change it to b
   ;  N = w     % else change it to w
   ), write(N). % and write value of N

注意我移动了 if/then/else 周围的括号.尝试遵循这个简单的语法,因为随意使用运算符(如 (->)/2、(;)/2 和 (,)/2)可能会引起一些令人不快的意外.Prolog 控制流可能难以调试...

Note I moved the parenthesis surrounding the if/then/else. Try to follow this simple syntax, because to a liberal use of operators (like (->)/2, (;)/2 and (,)/2) can cause some unpleasant surprise. Prolog control flow can be difficult to debug...

那段代码是无用的复杂:在 Prolog 中,尝试使用模式匹配而不是控制流:这个规则"以更简单的方式做同样的事情(除了写):

That code is useless complex: in Prolog, try to make use of pattern matching instead of control flow: this 'rule' does the same (apart the write) in simpler way:

change_player(w, b).
change_player(b, w).

这篇关于Prolog:连续更改两个已知值之间的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆