Advertisement
Average-user

Prolog/chess960

Dec 28th, 2017
427
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.08 KB | None | 0 0
  1. % Using SWI-Prolog 7.2.3
  2. % see https://en.wikipedia.org/wiki/Chess960 to understant what is this about.
  3.  
  4. :- use_module(library(random)).
  5.  
  6. even(N) :- 0 is N mod 2.
  7. odd(N) :- \+even(N).
  8.  
  9. index_of(Xs, X, N) :- nth0(N, Xs, X).
  10.  
  11. start_position(P) :-
  12.   Pieces = ['N','N','K','B','b','T','t','Q'],
  13.   permutation(Pieces, P),
  14.   index_of(P, 'T', IT),
  15.   index_of(P, 't', It),
  16.   index_of(P, 'K', IK),
  17.   IT < IK,
  18.   IK < It,   % The King must be between the two towers
  19.   index_of(P, 'B', IB),
  20.   index_of(P, 'b', Ib),
  21.   even(Ib),
  22.   odd(IB).   % Bishops must be in different colored squares
  23.  
  24. turn(t, 'T') :- !.
  25. turn(b, 'B') :- !.
  26. turn(X,   X).
  27.  
  28. % All valid Fischer Random Chess positions
  29. all_pos(Ps) :-
  30.   setof(P, start_position(P), Ps1),
  31.   maplist(maplist(turn), Ps1, Ps).
  32.  
  33. % Picks randomly, one of the 960 different positions.
  34. random_960_position(P) :-
  35.   all_pos(Ps),
  36.   random_member(P, Ps).
  37.  
  38. /*
  39.    | Example:
  40.      | -?  all_pos(Ps), length(Ps, L).
  41.      | Ps = ... L = 960
  42.      |
  43.      | ?- random_960_position(X).
  44.      | X = ['N', 'B', 'N', 'T', 'B', 'K', 'Q', 'T'].
  45. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement