Mark Molloy
Mark Molloy

Reputation: 13

Prolog | Can I continue execution after a false?

Using prolog, can I continue execution after a line returns false?

I have to create a tic-tac-toe game. I want to check for a winning state after each player's turn.

checkwin returns true when there is a winning state, but false otherwise. The issue then is that after it returns false, I can't move on to the next player's move.

How can I check it every turn, and continue to execute the code that follows the check? Is there a way to 'continue if false'?

adjustGame(PosX, PosY, Gameboard, Token) :-
    update(PosX, PosY, Gameboard, Newboard, Token),
    display(Newboard),
    checkwin(Newboard,Token),% This is false until the game has a winner
    play(Newboard,Token).    % but I want to execute this line until then

checkwin([A,B,C,D,E,F,G,H,I],T) :-
    same(A,B,C,T);
    same(D,E,F,T);
    same(G,H,I,T);
    same(A,D,G,T);
    same(B,E,H,T);
    same(C,F,I,T);
    same(A,E,I,T);
    same(C,E,G,T).

same(X,X,X,X).

Thanks!

Upvotes: 1

Views: 1593

Answers (1)

firefrorefiddle
firefrorefiddle

Reputation: 3805

Disjunction is the ; operator:

?- false ; X=3.
X = 3.

Think of it of if-else - if false then false else X=3:

?- true ; X=3.
true

?- check_win(...) ; play_game(...).
... 

There also is a full-fledge if-then-else:

?- true -> X=4 ; X=3. 
X = 4.

?- false -> X=4 ; X=3.
X = 3.

?- check_win(...) -> writeln("WIN"); play_game(...).
... 

Upvotes: 2

Related Questions