Prolog code

Posted on February 23, 2007

Example of how to draw NxM board in Prolog. Usefull when you need to show the state of a chess board or for games like wolves and sheep. Code from Simon Colton’s tutorial page.

127 cell(A,B) :-
128     L = [1,2,3,4,5,6,7,8],
129     member(A,L),
130     member(B,L).
131 
132 draw_board(Board) :-
133     write(  12345678\n),
134     write( +——–+),
135     findall(_,
136         (cell(A,B), draw_newline(A,B),
              draw_cell(A,B,Board),draw_endline(B)),
137         _),
138     write(\n +——–+\n\n).
139 
140 draw_newline(A,1) :-
141     write(\n),
142     write(A),
143     write(|).
144 draw_newline(_,X) :-
145     X=\=1.
146 
147 
148 draw_cell(A,B,[Wolves, _]) :-
149     member(A/B,Wolves),
150     write(w), !.
151 draw_cell(A,B,[_, Sheep]) :-
152     member(A/B,Sheep),
153     write(r), !.
154 draw_cell(_,_,[_, _]) :-
155     write( ).
156 
157 
158 draw_endline(8) :-
159     write(|).
160 draw_endline(X) :-
161     X=\=8.
162

Pass the state as a parameter
draw_board([[1/1,1/3,1/5,1/7],[2/4]]).
and it will display the board:

12345678
+——–+
1|w w w w |
2|   r    |
3|        |
4|        |
5|        |
6|        |
7|        |
8|        |
+——–+

Filed Under Uncategorized |

2 Comments so far
  1. TTT March 13, 2007 3:16 pm

    could you please send me
    the whole code of
    that project (sheep and 4 wolves)
    tamer00@hotmail.com

  2. Iouri Goussev March 13, 2007 5:48 pm

    what is your concordia email?

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name

Email

Website

Comments

For spam detection purposes, please copy the number 5214 to the field below:

© Copyright 0xDEADBEEFCAFE • Powered by Wordpress • Design by Sebastin.

free web hit counter