Prolog: Changing a variable between two known valu

2019-08-04 00:17发布

问题:

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).

I am trying to do this:

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

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

Can you tell me what Im doing wrong? Thankyou

回答1:

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

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...

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).