35
Expt: Aim: To implement Wumpus world problem in Java Theory: The WUMPUS WORLD Environment • The Wumpus computer game • The agent explores a cave consisting of rooms connected by passageways. • Lurking somewhere in the cave is the Wumpus, a beast that eats any agent that enters its room. • Some rooms contain bottomless pits that trap any agent that wanders into the room. • Occasionally, there is a heap of gold in a room. • The goal is to collect the gold and exit the world without being eaten. Typical Wumpus World: The agent always starts in the field [1, 1].The task of the agent is to find the gold, and return to the field [1, 1] and climb out of the cave. 1

wumpus program

Embed Size (px)

Citation preview

Expt:

Aim: To implement Wumpus world problem in Java

Theory:

The WUMPUS WORLD Environment

• The Wumpus computer game

• The agent explores a cave consisting of rooms connected by passageways.

• Lurking somewhere in the cave is the Wumpus, a beast that eats any agent that enters its room.

• Some rooms contain bottomless pits that trap any agent that wanders into the room.

• Occasionally, there is a heap of gold in a room.

• The goal is to collect the gold and exit the world without being eaten.

Typical Wumpus World:

The agent always starts in the field [1, 1].The task of the agent is to find the gold, and return to the field [1, 1] and climb out of the cave.

1

Program:

To implement Wumpus world problem in Java

import java.util.*;class Environment{Scanner scr=new Scanner(System.in);//char w[][]=new char[5][5];int np; //number of pitsint wp,gp; // wumpus position gold positionint pos[]; // position of pitsint b_pos[]=new int[20];int s_pos[]=new int[20];void accept(String w[][]){for(int i=0;i<20;++i){b_pos[i]=-1;s_pos[i]=-1;}

for(int i=0;i<5;++i)for(int j=0;j<5;++j)w[i][j]="";

int count=1;System.out.println("\n\n********* Wumpus World Problem *********\n-by Aditya Mandhare.\n");

System.out.println("The positions are as follows.");for(int i=1;i<=4;++i){System.out.println("\n-----------------------------------------------------------------");System.out.print("|\t");for(int j=1;j<=4;++j)System.out.print((count++)+"\t|\t");}System.out.println("\n-----------------------------------------------------------------");System.out.println("\nAgent start position: 13");w[4][1]="A";System.out.println("\nEnter the number of pits.");np=scr.nextInt();pos=new int[np];System.out.println("Positions of pit, gold and wumpus should not overlap.");System.out.println("Enter the position of pits.");for(int i=0;i<np;++i){pos[i]=scr.nextInt();

2

show_sense(pos[i],1,w);}System.out.println("Enter the position of wumpus.");wp=scr.nextInt();show_sense(wp,2,w);

System.out.println("Enter the position of gold.");gp=scr.nextInt();

insert(w);}

void insert(String w[][]){int temp=0;int count=0;int flag1=0,flag2=0;for(int i=0;i<np;++i){temp=pos[i];count=0;for(int j=1;j<=4;++j){for(int k=1;k<=4;++k){++count;if(count==temp)w[j][k]+="P";elseif(count==gp && flag1==0){w[j][k]+="G";flag1=1;}elseif(count==wp && flag2==0){w[j][k]+="W";flag2=1;}}}}

display(w);}

void show_sense(int a,int b,String w[][]){

3

int t1,t2,t3,t4;t1=a-1;t2=a+1;t3=a+4;t4=a-4;

if(a==5 || a==9)t1=0;if(a==8 || a==12)t2=0;if(a==4)t2=0;if(a==13)t1=0;

if(t3>16)t3=0;if(t4<0)t4=0;

//int temp[]=new int[4];

if(b==1){b_pos[0]=t1;b_pos[1]=t2;b_pos[2]=t3;b_pos[3]=t4;}elseif(b==2){s_pos[0]=t1;s_pos[1]=t2;s_pos[2]=t3;s_pos[3]=t4;}

int temp1,count;

for(int i=0;i<4;++i){if(b==1)temp1=b_pos[i];elsetemp1=s_pos[i];count=0;for(int j=1;j<=4;++j){for(int k=1;k<=4;++k){++count;if(count==temp1 && b==1 && !w[j][k].contains("B")){w[j][k]+="B";}elseif(count==temp1 && b==2 && !w[j][k].contains("S"))w[j][k]+="S";

4

}}} //display(w);}void display(String w[][]){System.out.println("\nThe environment for problem is as follows.\n");for(int i=1;i<=4;++i){System.out.println("\n-----------------------------------------------------------------");System.out.print("|\t");for(int j=1;j<=4;++j)System.out.print(w[i][j]+"\t|\t");}System.out.println("\n-----------------------------------------------------------------");}

}

class tiles{int safe=0;int unsafe=0;int wump=0;int pit=0;int gold=0;int doubt_pit=0;int doubt_wump=0;String env;int num=0;int br=0;int bl=0;int bu=0;int bd=0;int visited=0;int l,r,u,d;String back="";tiles(String s,int n){env=s;num=n;l=r=u=d=0;if(n==9 || n==5)bl=1;

if(n==8 || n==12)

5

br=1;

if(n==1){bu=1;bl=1;}if(n==13){bd=1;bl=1;}if(n==4){bu=1;br=1;}if(n==16){bd=1;br=1;}

}

int sense(){if(env.contains("B"))return 1;elseif(env.contains("S"))return 2;elseif(env.contains("G"))return 3;if(env.contains("W"))return 4;elsereturn 0;}

}

class wumpus {static int scream=0;static int score=0;static int complete=0;

static boolean check(tiles t){int temp=t.sense();

6

if(temp==1 || temp==2)return false;

return true;}public static void main(String args[]){Scanner scr=new Scanner(System.in);Environment e=new Environment();String w[][]=new String[5][5];e.accept(w);System.out.println("\n\nFinding the solution...");

tiles t[]=new tiles[17];int c=1;out:for(int i=1;i<5;++i){for(int j=1;j<5;++j){if(c>16)break out;t[c]=new tiles(w[i][j],c);++c;}}

t[13].safe=1;t[13].visited=1;

int pos=13;int condition;int limit=0;String temp1,temp2;do{++limit;condition=-1;

if(t[pos].env.contains("G")){complete=1;System.out.println("Gold Found!!");break;}

if(t[pos].br!=1 && t[pos].r!=1 && t[pos+1].doubt_pit<1 && t[pos+1].doubt_wump<1 && t[pos+1].pit!=1 && t[pos+1].wump!=1 && !(t[pos].back.contains("r") && (t[pos].l!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) )){

7

////////////

temp1="l";///////////t[pos].r=1;++pos;System.out.println("\nfront pos="+pos);++score;//t[pos].visited=1;////////////////t[pos].back+=temp1;////////////////condition=t[pos].sense();if(condition==3){complete=1;break;}elseif(condition==1 && t[pos].visited==0){if(t[pos].br!=1 && t[pos+1].safe!=1)t[pos+1].doubt_pit+=1;if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)t[pos-4].doubt_pit+=1;if(t[pos].bl!=1 && t[pos-1].safe!=1 )t[pos-1].doubt_pit+=1;if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)t[pos+4].doubt_pit+=1;

t[pos].safe=1;}elseif(condition==2 && t[pos].visited==0){if(t[pos].br!=1 && t[pos+1].safe!=1)t[pos+1].doubt_wump+=1;if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)t[pos-4].doubt_wump+=1;if(t[pos].bl!=1 && t[pos-1].safe!=1)t[pos-1].doubt_wump+=1;if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)t[pos+4].doubt_wump+=1;

t[pos].safe=1;}/*elseif(condition==4){score=score+100;t[pos].safe=1;}*/

8

elseif(condition==0)t[pos].safe=1;

t[pos].visited=1;}elseif(t[pos].bl!=1 && t[pos].l!=1 && t[pos-1].doubt_pit<1 && t[pos-1].doubt_wump<1 && t[pos-1].pit!=1 && t[pos-1].wump!=1 && !(t[pos].back.contains("l") && (t[pos].r!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) )){////////////////////temp1="r";///////////////////t[pos].l=1;pos=pos-1;System.out.println("\nback pos= "+pos);++score;//t[pos].visited=1;

//////////////////////

t[pos].back+=temp1;/////////////////////

condition=t[pos].sense();if(condition==3){complete=1;break;}elseif(condition==1 && t[pos].visited==0){if(t[pos].br!=1 && t[pos+1].safe!=1)t[pos+1].doubt_pit+=1;if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)t[pos-4].doubt_pit+=1;if(t[pos].bl!=1 && t[pos-1].safe!=1)t[pos-1].doubt_pit+=1;if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)t[pos+4].doubt_pit+=1;

t[pos].safe=1;}elseif(condition==2 && t[pos].visited==0){if(t[pos].br!=1 && t[pos+1].safe!=1)

9

t[pos+1].doubt_wump+=1;if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)t[pos-4].doubt_wump+=1;if(t[pos].bl!=1 && t[pos-1].safe!=1)t[pos-1].doubt_wump+=1;if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)t[pos+4].doubt_wump+=1;

t[pos].safe=1;}elseif(condition==0)t[pos].safe=1;

t[pos].visited=1;

}elseif(t[pos].bu!=1 && t[pos].u!=1 && (pos-4)>=1 && t[pos-4].doubt_pit<1 && t[pos-4].doubt_wump<1 && t[pos-4].pit!=1 && t[pos-1].wump!=1 && !(t[pos].back.contains("u") && (t[pos].l!=1 || t[pos].r!=1 || t[pos].d!=1) && check(t[pos]) )){/////////////////////

temp1="d";/////////////////////t[pos].u=1;pos=pos-4;System.out.println("\nUp pos= "+pos);++score;//t[pos].visited=1;

///////////////////////t[pos].back+=temp1;/////////////////////condition=t[pos].sense();if(condition==3){complete=1;break;}elseif(condition==1 && t[pos].visited==0){if(t[pos].br!=1 && t[pos+1].safe!=1)t[pos+1].doubt_pit+=1;if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)t[pos-4].doubt_pit+=1;if(t[pos].bl!=1 && t[pos-1].safe!=1)t[pos-1].doubt_pit+=1;if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)

10

t[pos+4].doubt_pit+=1;

t[pos].safe=1;}elseif(condition==2 && t[pos].visited==0){if(t[pos].br!=1 && t[pos+1].safe!=1)t[pos+1].doubt_wump+=1;if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)t[pos-4].doubt_wump+=1;if(t[pos].bl!=1 && t[pos-1].safe!=1)t[pos-1].doubt_wump+=1;if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)t[pos+4].doubt_wump+=1;

t[pos].safe=1;}elseif(condition==0)t[pos].safe=1;

t[pos].visited=1;}elseif(t[pos].bd!=1 && t[pos].d!=1 && (pos+4)<=16 && t[pos+4].doubt_pit<1 && t[pos+4].doubt_wump<1 && t[pos+4].pit!=1 && t[pos+4].wump!=1){/////////////////temp1="u";////////////////t[pos].d=1;pos=pos+4;System.out.println("\ndown pos= "+pos);++score;//t[pos].visited=1;

//////////////////

t[pos].back+=temp1;//////////////////condition=t[pos].sense();if(condition==3){complete=1;break;}elseif(condition==1 && t[pos].visited==0){if(t[pos].br!=1 && t[pos+1].safe!=1)

11

t[pos+1].doubt_pit+=1;if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)t[pos-4].doubt_pit+=1;if(t[pos].bl!=1 && t[pos-1].safe!=1)t[pos-1].doubt_pit+=1;if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)t[pos+4].doubt_pit+=1;

t[pos].safe=1;}elseif(condition==2 && t[pos].visited==0){if(t[pos].br!=1 && t[pos+1].safe!=1)t[pos+1].doubt_wump+=1;if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)t[pos-4].doubt_wump+=1;if(t[pos].bl!=1 && t[pos-1].safe!=1)t[pos-1].doubt_wump+=1;if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)t[pos+4].doubt_wump+=1;

t[pos].safe=1;}elseif(condition==0)t[pos].safe=1;

t[pos].visited=1;}elseif(limit>50){int temp3=pos;int flag_1=0,flag2=0,flag3=0,flag4=0;

System.out.println("\nCurrently at position "+temp3+".\nThinking....");

//if(!(t[pos].back.contains("r") && (t[pos].l!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) ))while(t[pos].visited==1 && t[pos].br!=1){++pos;++score;}

if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].br==1 && t[pos].visited==1 && t[pos].safe!=1)){//System.out.println("\nUnsuccessful at pos "+pos);

12

pos=temp3;//System.out.println("\nBack at pos "+pos);flag_1=1;}

if(flag_1==0)t[pos].back+="l";

//if(!(t[pos].back.contains("u") && (t[pos].l!=1 || t[pos].r!=1 || t[pos].d!=1) && check(t[pos]) ))while(pos+4>=1 && t[pos].bu!=1 && t[pos].visited==1){pos-=4;++score;}

if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].bu==1 && t[pos].visited==1 && t[pos].safe!=1)){//System.out.println("\nUnsuccessful at pos "+pos);pos=temp3;//System.out.println("\nBack at pos "+pos);flag3=1;}

if(flag3==0)t[pos].back+="d";

//if(!(t[pos].back.contains("l") && (t[pos].r!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) ))while(t[pos].visited==1 && t[pos].bl!=1){--pos;++score;}

if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].bl==1 && t[pos].visited==1 && t[pos].safe!=1)){//System.out.println("\nUnsuccessful at pos "+pos);pos=temp3;//System.out.println("\nBack at pos "+pos);flag2=1;}

if(flag2==0)t[pos].back+="r";

//if(!(t[pos].back.contains("d") && (t[pos].l!=1 || t[pos].r!=1 || t[pos].u!=1) && check(t[pos]) ))while(pos+4<=16 && t[pos].bd!=1 && t[pos].visited==1){

13

pos+=4;++score;}

if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].bd==1 && t[pos].visited==1 && t[pos].safe!=1)){//System.out.println("\nUnsuccessful at pos "+pos);pos=temp3;//System.out.println("\nBack at pos "+pos);flag4=1;} //t[pos-1].r=0;//++pos;//if(!t[pos].env.contains("P") && !t[pos].env.contains("W"))

if(flag4==0)t[pos].back+="u";

t[pos].safe=1;t[pos].visited=1;System.out.println("reached at position "+pos);limit=0;}if(t[pos].env.contains("W") && scream!=1){score+=100;scream=1;t[pos].safe=1;System.out.println("\n\nWumpus killed >--0-->");t[pos].env.replace("W"," ");for(int l=1;l<=16;++l){t[l].doubt_wump=0;t[l].env.replace("S"," ");}}

if(t[pos].env.contains("P")){score+=50;t[pos].pit=1;System.out.println("\n\nFallen in pit of position "+pos+".");}

for(int k=1;k<=16;++k){if(t[k].doubt_pit==1 && t[k].doubt_wump==1){t[k].doubt_pit=0;

14

t[k].doubt_wump=0;t[k].safe=1;}}

for(int y=1;y<=16;++y){if(t[y].doubt_wump>1){t[y].wump=1;for(int h=1;h<=16;++h){if(h!=y){t[h].doubt_wump=0;t[h].env.replace("S"," ");}}

}

}

///////////////////////////for(int y=1;y<=16;++y){if(t[y].doubt_pit>1){t[y].pit=1;//System.out.println("\nPit confirmed at position "+y);}}///////////////////////////

try{Thread.sleep(200);}catch(Exception p){}

}while(complete==0);

if(complete==1){//score=score*2;//if(scream==1)//score-=100;

score*=-1;score+=1000;}

15

System.out.println("The score of the agent till he reaches gold is "+score+".\nNow he will return back following the best explored path.");

}}

/* OUTPUT 1

C:\Users\programs>javac wumpus.java

C:\Users\programs>java wumpus

********* Wumpus World Problem *********

The positions are as follows.

-----------------------------------------------------------------| 1 | 2 | 3 | 4 |-----------------------------------------------------------------| 5 | 6 | 7 | 8 |-----------------------------------------------------------------| 9 | 10 | 11 | 12 |-----------------------------------------------------------------| 13 | 14 | 15 | 16 |-----------------------------------------------------------------

Agent start position: 13

Enter the number of pits.3Positions of pit, gold and wumpus should not overlap.Enter the position of pits.4 7 15Enter the position of wumpus.5Enter the position of gold.6

The environment for problem is as follows.

-----------------------------------------------------------------| S | | B | P |-----------------------------------------------------------------| W | BSG | P | B |

16

-----------------------------------------------------------------| S | | B | |-----------------------------------------------------------------| A | B | P | B |-----------------------------------------------------------------

Finding the solution...

front pos=14

back pos= 13

Up pos= 9

front pos=10

front pos=11

back pos= 10

Up pos= 6Gold Found!!The score of the agent till he reaches gold is 993.Now he will return back following the best explored path.

Conclusion: Thus, We have studied and implemented wumpus world.

17

Expt:

Aim: Study of Prolog

Theory:

1 Starting Prolog and loading a program

The SWI-Prolog executable swipl-win.exe can be started from the StartMenu or by opening a .pl file holding Prolog program text from the Windows explorer.1 The installation folder (by default C:\Program Files\swipl) contains a subfolder demo with the file likes.pl. This file can be opened in Prolog from the StartMenu, by opening likes.pl in the Windows explorer or by using the following command in the Prolog application. Be sure to get the quotes right and terminate the command with a full-stop (.).

?- [swi('demo/likes')].

If Prolog is started from the start menu it is passed the option --win_app, which causes it to start in the local equivalent of MyDocuments\Prolog. This folder is created if it does not exist.

2 Executing a query

After loading a program, one can ask Prolog queries about the program. The query below asks Prolog what food `sam' likes. The system responds with X = <value> if it can prove the goal for a certain X. The user can type the semi-colon (;)2 if (s)he wants another solution, or RETURN if (s)he is satisfied, after which Prolog will say Yes. If Prolog answers No, it indicates it cannot find any (more) answers to the query. Finally, Prolog can answer using an error message to indicate that the query or program contains an error.

?- likes(sam, X).

X = dahl ;

X = tandoori ;

...

X = chips ;

No?-

3 Menu commands

The SWI-Prolog console provided by swipl-win.exe has a menu for accessing the most commonly used commands. We assume not all menu entries need to be explained in details. We make some exceptions:

File/Reload modified files

18

This menu reloads all loaded source files that have been modified using the make/0 command.

File/Navigator ...

Opens an explorer-like view on Prolog files and the predicates they contain.

Settings/Font ...

Allows for changing the font of the console. On some installations the default font gives redraw and cursor dislocation problems. In this case you may wish to select an alternative. Some built-in commands assume non-proportional fonts.

Settings/User init file ...

Edits the user personalisation file. If no such file exists, it first installs a default file as pl.ini that contains commonly used settings in comments.

Settings/Stack sizes ...

Allows for defining the maximum size to which the various Prolog stacks are allowed to grow. The system defaults are chosen to make erroneous programs fail quickly on modest hardware. Programs with large data structures or many choice-points often need larger stacks. Note that an active Prolog process growing over the size of the physical memory of your computer can make the system extremely slow.

Run/Interrupt

Try to interrupt the running Prolog process. This is the same as using Control-C. Sometimes interrupts are not honoured or take very long to process. Closing the window twice provides a way to force Prolog to stop.

Run/New thread

Creates a new interactor window running in a separate thread of execution. This may be used to inspect the database or program while the main task continues.

Debug/Edit spy points ...

Edit break-points on predicates. From the PceEmacs editor break-points can also be set on specific calls from specific clauses.

Debug/Graphical debugger ...

Use the source-level debugger on the next spy- or break-point or other call that enables the debugger.

Help

19

The help menu provides various starting points to related documents. Items flagged with (on www) open your default internet browser on a page of the SWI-Prolog website.

4 Editing Prolog programs

There are three options for editing. One is to run an editor of choice in a separate window and use the make/0 command described below to reload modified files. In addition to this option Prolog can be used to locate predicates, modules and loaded files by specifying the editor of choice for use with the edit/1 command, described below. This is achieved by editing the personalisation file) and following the instructions in the comments.

The default editor is built-in editor called PceEmacs. This editor provides colourisation support based on real-time parsing and cross-reference analysis of the program.

Other options for editing include GNU-Emacs, SWI-Prolog-Editor and the Eclipse-based PDT environment.

5 Some useful commands

This section provides a very brief overview of important or commonly used SWI-Prolog predicates to control the environment.

consult(:File)

Load a source file. On Windows, folders may be specified with the DOS/Windows \, which must be escaped, or by using the POSIX standard /. Especially when used in source code, / is to be preferred as it is portable. A Prolog list ([ ... ]) can be used to abbreviate the consult command. The file extension (.pl as well as the selected alternative) can be omitted. Here are some examples:

?- consult(likes). Load likes.pl from the current folder (see pwd/0).

?- ['C:/Program Files/pl/demo/likes'] Load likes.pl using absolute path.

?- ['C:\\Program Files\\pl\\demo\\likes'] Same using Windows-style path name

pwd

Print working directory (folder).

ls

List files in current directory.

edit

If Prolog is started by opening a .pl file in the explorer, edit this file. Also available from the menu.

20

edit(+Spec)

Edit file, predicate, module, etc., with the given name. If multiple items are named Spec it prompts for the desired alternative.

make

Reload all files that have been changed since they were last loaded. Normally used after editing one or more files.

gtrace

Start the graphical debugger. There are three ways to use this. Entered as a single goal at the top-level, the next query will be traced. Alternatively it can be used in conjunction with the goal to be debugged: ?- gtrace, run. and finally you can include it in your program to start tracing at a particular point or under a particular condition:

..., (var(X) -> gtrace ; true), ...,

trace

Same as gtrace, but text-based on the console.

apropos(+Keyword)

Search for all predicates that contain Keyword in their name or short description. If a GUI environment is available the results are hyperlinks. Otherwise use help/1 to get details on selected hits.

help(+Spec)

Give help on Spec, which is normally the name of a predicate or C interface function.

The installation

1 Supported Windows versions

SWI-Prolog requiring Windows XP or later (XP, Vista, Windows-7). The download site of SWI-Prolog contains older binaries that run on older versions of Windows. We provide both 32-bit and 64-bit installers.

2 Choosing the file extension

By default, Prolog uses the .pl extension to indicate Prolog source files. Unfortunately this extension conflicts with the Perl language. If you want to use both on the same Windows machine SWI-Prolog allows you to choose a different extension during the installation. The extension .pro

21

is a commonly used alternative. If portability is an issue, it is advised to use the alternative extension only for the load file, the source file that loads the entire program, and use the normal .pl extension for libraries and files loaded from other files.

3 Installed programs

The table below lists the installed components. Some components are marked (32-bits) or (64-bits). Most of this is because the 64-bits version is built using more recent tools and from more recent versions of required libraries using different naming conventions. This will probably be synchronised in the future.

Programs

bin\swipl-win.exe Default Windows application for interactive use.

bin\swipl.exe Console-based version for scripting purposes.

Utilities

bin\swipl-ld.exe Linker front-end to make single-file mixed Prolog/C/C++ executables.

bin\plrc.exe Manipulate Prolog resource files.

Important directories

bin Executables and DLL files

library Prolog library

boot Sources for system predicates

include C/C++ header files for embedding or to create extensions

xpce XPCE graphics system

xpce\prolog\lib XPCE/Prolog library

DLLs and other supporting files

boot32.prc Initial Prolog state (32-bits)

boot64.prc Initial Prolog state (64-bits)

\bin\libswipl.dll The Prolog kernel

\bin\plterm.dll The window for swipl-win.exe

22

\bin\pthreadVC2.dll POSIX thread runtime library (64-bits)

Extension DLLs (plugins)

\bin\cgi.dll Gather CGI GET and POST arguments

\bin\double_metaphone.dll Soundex (sounds similar)

\bin\memfile.dll In-memory temporary `files'

\bin\odbc4pl.dll ODBC interface

\bin\plregtry.dll Windows registry interface

\bin\porter_stem.dll Porter stemming implementation

\bin\random.dll Portable random number generator

\bin\rdf_db.dll RDF database

\bin\readutil.dll Fast reading utility

\bin\sgml2pl.dll SGML/XML parser

\bin\socket.dll Prolog socket interface

\bin\table.dll Access structured files as tables

\bin\time.dll Timing and alarm library

\bin\xpce2pl.dll The XPCE graphics system

\bin\zlib1.dll Compression library (32-bit)

\bin\zlibwapi.dll Compression library (64-bit)

\bin\zlib4pl.dll Compression library interface

4 Installed Registry keys and menus

The filetype .pl or chosen alternative (see section 3.2) is associated to swipl-win.exe. A chosen folder (default SWI-Prolog) is added to the start menu holding shortcuts to Prolog and some

23

related utilities. The following registry keys are in use. The 64-bit version uses Prolog64 instead of Prolog as a key to accommodate installation of both versions on the same machine. Note that opening a .pl file can be associated with one of the installed Prolog versions only.

HKEY_LOCAL_MACHINE\Software\SWI\Prolog

fileExtension Extension used for Prolog files

group Start menu group

home Installation directory

HKEY_CURRENT_USER\Software\SWI\Plwin\Console

Note: thread-windows store the same info in sub-keys

Height Height of window in character units

Width Width of window in character units

X Left edge of window in pixel units

Y Top edge of window in pixel units

SaveLines Number of lines available for scrollback

5 Execution level

The installer asks for the admin execution level (Vista and later) to be able to write shortcuts and registry keys.

6 Creating a desktop menu item

If you want a desktop entry for SWI-Prolog, right-drag swipl-win.exe to the desktop and select `Create shortcut'. Then edit the properties and add --win_app to the command line to make the application start in MyDocuments\Prolog.

Conclusion: Thus, We have studied SWI Prolog.

24

Expt:

Aim: Implementation of n-Queen using prolog.

Theory:

Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics.

Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is declarative: the program logic is expressed in terms of relations, represented as facts and rules. A computation is initiated by running a query over these relations.

Algorithm for n-queen problem:solution(Queens) :- permutation([1,2,3,4,5,6,7,8], Queens), safe(Queens).

permutation([],[]).

permutation([Head|Tail],PermList) :- permutation(Tail,PermTail), del(Head,PermList,PermTail).

del(Item,[Item|List],List).

del(Item,[First|List],[First|List1]) :- del(Item,List,List1).

safe([]).

safe([Queen|Others]) :- safe(Others), noattack(Queen,Others,1).

noattack(_,[],_).

noattack(Y,[Y1|Ylist],Xdist) :- Y1-Y=\=Xdist, Y-Y1=\=Xdist, Dist1 is Xdist + 1, noattack(Y,Ylist,Dist1).

25

Program:/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - N Queens animation.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

:- use_module(library(clpfd)).

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Constraint posting.- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

n_queens(N, Qs) :- length(Qs, N), Qs ins 1..N, safe_queens(Qs).

safe_queens([]).safe_queens([Q|Qs]) :- safe_queens(Qs, Q, 1), safe_queens(Qs).

safe_queens([], _, _).safe_queens([Q|Qs], Q0, D0) :- Q0 #\= Q, abs(Q0 - Q) #\= D0, D1 #= D0 + 1, safe_queens(Qs, Q0, D1).

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Animation.

For each N of the domain of queen Q, a reified constraint of the form

Q #= N #<==> B

is posted. When N vanishes from the domain, B becomes 0. A frozen goal then emits PostScript instructions for graying out the field. When B becomes 1, the frozen goal emits instructions for placing the queen. On backtracking, the field is cleared.- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

animate(Qs) :- animate(Qs, Qs, 1).

animate([], _, _).animate([_|Rest], Qs, N) :- animate_(Qs, 1, N), N1 #= N + 1, animate(Rest, Qs, N1).

26

animate_([], _, _).animate_([Q|Qs], C, N) :- freeze(B, queen_value_truth(C,N,B)), Q #= N #<==> B, C1 #= C + 1, animate_(Qs, C1, N).

queen_value_truth(Q, N, 1) :- format("~w ~w q\n", [Q,N]).queen_value_truth(Q, N, 0) :- format("~w ~w i\n", [Q,N]).queen_value_truth(Q, N, _) :- format("~w ~w c\n", [Q,N]), false.

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PostScript definitions.

Sample instructions, with these definitions loaded:

2 init % initialize a 2x2 board 1 1 q % place a queen on 1-1 1 2 q 1 2 c % remove the queen from 1-2 2 2 i % gray out 2-2- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

postscript --> "/init { /N exch def 340 N div dup scale -1 -1 translate \ /Palatino-Roman 0.8 selectfont 0 setlinewidth \ 1 1 N { 1 1 N { 1 index c } for pop } for } bind def \ /r { translate 0 0 1 1 4 copy rectfill 0 setgray rectstroke } bind def \ /i { gsave 0.5 setgray r grestore } bind def \ /q { gsave r 0.5 0.28 translate (Q) dup stringwidth pop -2 div 0 moveto \ 1 setgray show grestore } bind def \ /c { gsave 1 setgray r grestore } bind def\n".

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Communication with gs.- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

show(N, Options, Qs) :- N #> 0, n_queens(N, Qs), open(pipe('gs -dNOPROMPT -g680x680 -dGraphicsAlphaBits=2 -r144 -q'), write, Out, [buffer(false)]), tell(Out), phrase(postscript, Ps), format("~s ~w init\n", [Ps,N]), call_cleanup((animate(Qs),labeling(Options, Qs)), close(Out)).

27

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Examples:

?- n_queens(8, Qs), labeling([ff], Qs). Qs = [1, 5, 8, 6, 3, 7, 2, 4] ; Qs = [1, 6, 8, 3, 7, 4, 2, 5] .

?- n_queens(100, Qs), labeling([ff], Qs). Qs = [1, 3, 5, 57, 59, 4, 64, 7, 58|...] .

?- show(8, [ff], Qs). Qs = [1, 5, 8, 6, 3, 7, 2, 4] .

?- show(N, [ff], Qs).

Conclusion: Thus, n- queen program using prolog is implemented.

28