/* Directions for use. 1. Download and install SWI-Prolog (freeware on Web): www.swi-prolog.org/ 2. Download the Tic-Toe-Prolog (remember file location). 3. Run SWI-Prolog. 4. From within Prolog: Use FILE menu option to Load (Prologese: "Consult") the Tic-tac-toe program from the remembered file location. 5. Enter this line into the Prolog interface (main window): play. Lower case letters! Period at end! 6. Play the computer by entering your move, e.g.: 5. if you want to put your move in the center square. Think of the squares as numbered, so: 1 2 3 4 5 6 7 8 9 That is, to make a move type: . 7. To interrupt the game, press C and together, or other "interrupt" indications. (See SWI documentation). */ :-dynamic opp/1. :-dynamic com/1. opp([]). com([]). dynamic:- opp/1. dynamic:- com/1. play:- display, read(Input), process(Input, Message), write(Message),nl, play. display:- opp(L1), com(L2),!, write('You: '), write(L1), nl, write('Computer: '), write(L2), nl. % Illegal Moves process(Input, 'Square occupied by your piece!'):- opp(Old), element_of(Input,Old), !. process(Input, 'Square occupied by computer piece!'):- com(Old), element_of(Input,Old), !. % Go for win process(Input, 'I win.'):- opp(OldOpp), NewOpp=[Input|OldOpp], com(Old), element_of(E1,Old), element_of(E2,Old), not(E1=E2), row(Row), element_of(E1,Row), element_of(E2,Row), element_of(E3,Row), not(E3=E1), not(E3=E2), not_element_of(E3,NewOpp), asserta(opp(NewOpp)), asserta(com([E3|Old])). % Block opponent's potential win process(Input, 'I will block your potential row.'):- opp(OldOpp), NewOpp=[Input|OldOpp], com(Old), element_of(E1,NewOpp), element_of(E2,NewOpp), not(E1=E2), row(Row), element_of(E1,Row), element_of(E2,Row), element_of(E3,Row), not(E3=E1), not(E3=E2), not_element_of(E3,Old), asserta(opp(NewOpp)), asserta(com([E3|Old])). % Punt process(Input, 'I just moved.'):- opp(OldOpp), NewOpp=[Input|OldOpp], com(Old), important(Important), element_of(E3,Important), not_element_of(E3, Old), not_element_of(E3,NewOpp), asserta(opp(NewOpp)), asserta(com([E3|Old])). important([5,1,3,7,8,2,4,6,8]). row([1,2,3]). row([1,5,9]). row([1,4,7]). row([2,5,8]). row([3,6,9]). row([3,5,7]). row([4,5,6]). row([7,8,9]). /* General Utilities */ element_of(Head, [Head|_]). element_of(X, [_|Tail]) :- element_of(X, Tail). number_of_elements_of(1, [X]):- !. number_of_elements_of(N, [_|X]):- number_of_elements_of(X), N is X+1. append([], List, List). append([X|L1], L2, [X|L3]) :- append(L1, L2, L3). not_element_of(Element,List):- element_of(Element,List), !, fail. not_element_of(_,_).