📄 queens.pl
字号:
/********************************************************************
Constraint-based Graphical Programming in B-Prolog
%
n-queen puzzle
*********************************************************************/
go:-
write('N=?'),read(N),queens(N,Qs),!,drawQueens(N,Qs).
queens(N,List):-
length(List,N),
List in 1..N,
constrain_queens(List),
labeling_ff(List).
constrain_queens([]).
constrain_queens([X|Y]):-
safe(X,Y,1),
constrain_queens(Y).
safe(_,[],_).
safe(X,[Y|T],K):-
noattack(X,Y,K),
K1 is K+1,
safe(X,T,K1).
noattack(X,Y,K):-
X #\= Y,
X+K #\= Y,
X-K #\= Y.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
drawQueens(N,Qs):-
write(user,'draw queens ....'),nl(user),
drawQueens(0,Qs,Comps,Comps1),
drawBoard(N,Comps1,[]),
cgStartRecord(queens),
cgShow(Comps).
cgStopRecord.
drawBoard(N,Comps,CompsR):-
drawHorizontalLines(0,N,Comps,Comps1),
drawVerticalLines(0,N,Comps1,CompsR).
drawHorizontalLines(I,N,Comps,CompsR):-I>N,!,Comps=CompsR.
drawHorizontalLines(I,N,Comps,CompsR):-
cgLine(Line),
cgDefaultWindow(Win),
Win^leftMargin #= LM,
Win^topMargin #= TM,
Line^x1 #= LM, Line^y1 #= 5*I+TM,
Line^x2 #= 5*N+LM, Line^y2 #= Line^y1,
Comps=[Line|Comps1],
I1 is I+1,
drawHorizontalLines(I1,N,Comps1,CompsR).
drawVerticalLines(I,N,Comps,CompsR):-I>N,!,Comps=CompsR.
drawVerticalLines(I,N,Comps,CompsR):-
cgLine(Line),
cgDefaultWindow(Win),
Win^leftMargin #= LM,
Win^topMargin #= TM,
Line^x1 #= 5*I+LM, Line^y1 #= TM,
Line^x2 #= Line^x1, Line^y2 #= N*5+TM,
Comps=[Line|Comps1],
I1 is I+1,
drawVerticalLines(I1,N,Comps1,CompsR).
drawQueens(_I,[],Comps,CompsR):-Comps=CompsR.
drawQueens(I,[J|Js],Comps,CompsR):-
cgSquare(S),
cgDefaultWindow(Win),
Win^leftMargin #= LM,
Win^topMargin #= TM,
S^x #= I*5+LM,
S^y #= (J-1)*5+TM,
S^width #= 5,
S^height #= 5,
S^color #= red,
Comps=[S|Comps1],
I1 is I+1,
drawQueens(I1,Js,Comps1,CompsR).
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -