Diogo Costa
Diogo Costa

Reputation: 1

How to use cut while trying random numbers until a condition is met

I'm coding a board game similar to checkers using prolog and I have this function that tests random generated numbers. I want it to return the first instance that works but, for some reason, it fails after finding it because it tries to redo in what I can only guess is an attempt to find other suitable solutions.

%cell_status(+Board, +pos(X,Y), -Status)
cell_status([cell(X,Y,S)|_], pos(X,Y), Status) :-
    Status = S, !.                                           
cell_status([_|T], pos(X,Y), Status) :-
    cell_status(T, pos(X,Y), Status).

%select_random_piece(+Board, +Player, -X, -Y)
select_random_piece(Board, Player, X, Y) :- 
    random(0, 6, X_tmp),
    random(0, 5, Y_tmp),
    write('testing X: '), write(X_tmp), nl,
    write('testing Y: '), write(Y_tmp), nl,
    cell_status(Board, pos(X_tmp,Y_tmp), Status),
    (%if
        Status == Player ->
     %then
        X is X_tmp,
        Y is Y_tmp;
     %else
         select_random_piece(Board, Player, X_tmp, Y_tmp),
         X is X_tmp, Y is Y_tmp
    ).

I tried debugging using trace and verified that after cell_status exits with a correct Status value it tries to redo cell_status again and fails. I also checked that cell_status works fine by itself.

How can I use cut in order to stop it from finding other solutions? Or am I missinterpreting the problem?

Upvotes: 0

Views: 62

Answers (1)

brebs
brebs

Reputation: 4456

Looks like this is all you need, for select_random_piece:

select_random_piece(Board, Player, X, Y) :- 
    between(0, 6, X),
    between(0, 5, Y),
    cell_status(Board, pos(X,Y), Player).

between creates choicepoints, for Prolog's inference engine to backtrack to, in search of a solution.

Let's avoid the complication of random, until fundamentals such as backtracking are understood.

Upvotes: 0

Related Questions