Information Technology Reference
In-Depth Information
Figure 10.6.
A Prolog program for tic-tac-toe
tictactoe.pl
player(x). player(o). % This is the tic-tac-toe game.
initial_state([-,-,-,-,-,-,-,-,-],x). % x moves first.
game_over(S,_,Q) :- three_in_row(S,Q). % A winner
game_over(S,_,neither) :- \+ legal_move(S,_,_,_). % A tie
three_in_row([P,P,P,_,_,_,_,_,_],P) :- player(P).
three_in_row([_,_,_,P,P,P,_,_,_],P) :- player(P).
three_in_row([_,_,_,_,_,_,P,P,P],P) :- player(P).
three_in_row([P,_,_,P,_,_,P,_,_],P) :- player(P).
three_in_row([_,P,_,_,P,_,_,P,_],P) :- player(P).
three_in_row([_,_,P,_,_,P,_,_,P],P) :- player(P).
three_in_row([P,_,_,_,P,_,_,_,P],P) :- player(P).
three_in_row([_,_,P,_,P,_,P,_,_],P) :- player(P).
legal_move([-,B,C,D,E,F,G,H,I],P,1,[P,B,C,D,E,F,G,H,I]).
legal_move([A,-,C,D,E,F,G,H,I],P,2,[A,P,C,D,E,F,G,H,I]).
legal_move([A,B,-,D,E,F,G,H,I],P,3,[A,B,P,D,E,F,G,H,I]).
legal_move([A,B,C,-,E,F,G,H,I],P,4,[A,B,C,P,E,F,G,H,I]).
legal_move([A,B,C,D,-,F,G,H,I],P,5,[A,B,C,D,P,F,G,H,I]).
legal_move([A,B,C,D,E,-,G,H,I],P,6,[A,B,C,D,E,P,G,H,I]).
legal_move([A,B,C,D,E,F,-,H,I],P,7,[A,B,C,D,E,F,P,H,I]).
legal_move([A,B,C,D,E,F,G,-,I],P,8,[A,B,C,D,E,F,G,P,I]).
legal_move([A,B,C,D,E,F,G,H,-],P,9,[A,B,C,D,E,F,G,H,P]).
A Prolog program for tic-tac-toe is shown in figure 10.6. As before, the predi-
cates player , initial_state , game_over , and legal_move are defined. The predicate
three_in_row is used to check if a player's mark (either x or o ) completes one of
the three horizontal lines, three vertical lines, or two diagonal lines (and hence the
eight clauses). The legal_move predicate has nine clauses, one for each of the possi-
ble moves. In each case, it confirms that there is a - in the appropriate position for
the move and replaces the - by the player's mark in the new state, using variables to
leave all the other eight positions unchanged.
If this program is loaded with the general game player, it can show how to make a
good move in various states of the game. For example, suppose X first put his mark in
position 1, and then O put hers in position 2. The options X now has are the following:
?- win_move([x,o,-,-,-,-,-,-,-],x,M).
M=4 ;
% A surprising move for X, perhaps
M=5 ;
% The center
M=7 ;
% A corner but not 3 or 9
No
Search WWH ::




Custom Search