-
Notifications
You must be signed in to change notification settings - Fork 0
/
TicTacToe.pl
744 lines (583 loc) · 17 KB
/
TicTacToe.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% CST 381 -– Artificial Intelligence
%%% Robert Pinchbeck
%%% Final Project
%%% Due December 20, 2006
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% A Prolog Implementation of Tic-Tac-Toe
%%% using the minimax strategy
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/*
The following conventions are used in this program...
Single letter variables represent:
L - a list
N - a number, position, index, or counter
V - a value (usually a string)
A - an accumulator
H - the head of a list
T - the tail of a list
For this implementation, these single letter variables represent:
P - a player number (1 or 2)
B - the board (a 9 item list representing a 3x3 matrix)
each "square" on the board can contain one of 3 values: x ,o, or e (for empty)
S - the number of a square on the board (1 - 9)
M - a mark on a square (x or o)
E - the mark used to represent an empty square ('e').
U - the utility value of a board position
R - a random number
D - the depth of the minimax search tree (for outputting utility values, and for debugging)
Variables with a numeric suffix represent a variable based on another variable.
(e.g. B2 is a new board position based on B)
For predicates, the last variable is usually the "return" value.
(e.g. opponent_mark(P,M), returns the opposing mark in variable M)
Predicates with a numeric suffix represent a "nested" predicate.
e.g. myrule2(...) is meant to be called from myrule(...)
and myrule3(...) is meant to be called from myrule2(...)
There are only two assertions that are used in this implementation
asserta( board(B) ) - the current board
asserta( player(P, Type) ) - indicates which players are human/computer.
*/
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% FACTS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
next_player(1, 2). %%% determines the next player after the given player
next_player(2, 1).
inverse_mark('x', 'o'). %%% determines the opposite of the given mark
inverse_mark('o', 'x').
player_mark(1, 'x'). %%% the mark for the given player
player_mark(2, 'o').
opponent_mark(1, 'o'). %%% shorthand for the inverse mark of the given player
opponent_mark(2, 'x').
blank_mark('e'). %%% the mark used in an empty square
maximizing('x'). %%% the player playing x is always trying to maximize the utility of the board position
minimizing('o'). %%% the player playing o is always trying to minimize the utility of the board position
corner_square(1, 1). %%% map corner squares to board squares
corner_square(2, 3).
corner_square(3, 7).
corner_square(4, 9).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% MAIN PROGRAM
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
run :-
hello, %%% Display welcome message, initialize game
play(1), %%% Play the game starting with player 1
goodbye %%% Display end of game message
.
run :-
goodbye
.
hello :-
initialize,
% cls,
nl,
nl,
nl,
write('Welcome to Tic-Tac-Toe.'),
read_players,
output_players
.
initialize :-
random_seed, %%% use current time to initialize random number generator
blank_mark(E),
asserta( board([E,E,E, E,E,E, E,E,E]) ) %%% create a blank board
.
goodbye :-
board(B),
nl,
nl,
write('Game over: '),
output_winner(B),
retract(board(_)),
retract(player(_,_)),
read_play_again(V), !,
(V == 'Y' ; V == 'y'),
!,
run
.
read_play_again(V) :-
nl,
nl,
write('Play again (Y/N)? '),
read(V),
(V == 'y' ; V == 'Y' ; V == 'n' ; V == 'N'), !
.
read_play_again(V) :-
nl,
nl,
write('Please enter Y or N.'),
read_play_again(V)
.
read_players :-
nl,
nl,
write('Number of human players? '),
read(N),
set_players(N)
.
set_players(0) :-
asserta( player(1, computer) ),
asserta( player(2, computer) ), !
.
set_players(1) :-
nl,
write('Is human playing X or O (X moves first)? '),
read(M),
human_playing(M), !
.
set_players(2) :-
asserta( player(1, human) ),
asserta( player(2, human) ), !
.
set_players(N) :-
nl,
write('Please enter 0, 1, or 2.'),
read_players
.
human_playing(M) :-
(M == 'x' ; M == 'X'),
asserta( player(1, human) ),
asserta( player(2, computer) ), !
.
human_playing(M) :-
(M == 'o' ; M == 'O'),
asserta( player(1, computer) ),
asserta( player(2, human) ), !
.
human_playing(M) :-
nl,
write('Please enter X or O.'),
set_players(1)
.
play(P) :-
board(B), !,
output_board(B), !,
not(game_over(P, B)), !,
make_move(P, B), !,
next_player(P, P2), !,
play(P2), !
.
%.......................................
%
% square
%.......................................
% The mark in a square(N) corresponds to an item in a list, as follows:
square([M,_,_,_,_,_,_,_,_],1,M).
square([_,M,_,_,_,_,_,_,_],2,M).
square([_,_,M,_,_,_,_,_,_],3,M).
square([_,_,_,M,_,_,_,_,_],4,M).
square([_,_,_,_,M,_,_,_,_],5,M).
square([_,_,_,_,_,M,_,_,_],6,M).
square([_,_,_,_,_,_,M,_,_],7,M).
square([_,_,_,_,_,_,_,M,_],8,M).
square([_,_,_,_,_,_,_,_,M],9,M).
%.......................................
% win
%.......................................
% Players win by having their mark in one of the following square configurations:
% Controle d'une victoire eventuelle
% -> Lucas
win([M,M,M, _,_,_, _,_,_],M).
win([_,_,_, M,M,M, _,_,_],M).
win([_,_,_, _,_,_, M,M,M],M).
win([M,_,_, M,_,_, M,_,_],M).
win([_,M,_, _,M,_, _,M,_],M).
win([_,_,M, _,_,M, _,_,M],M).
win([M,_,_, _,M,_, _,_,M],M).
win([_,_,M, _,M,_, M,_,_],M).
%.......................................
% move
%.......................................
% applies a move on the given board
% (put mark M in square S on board B and return the resulting board B2)
%
move(B,S,M,B2) :-
set_item(B,S,M,B2)
.
%.......................................
% game_over
%.......................................
% determines when the game is over
%
game_over(P, B) :-
game_over2(P, B)
.
game_over2(P, B) :-
opponent_mark(P, M), %%% game is over if opponent wins
win(B, M)
.
game_over2(P, B) :-
blank_mark(E),
not(square(B,S,E)) %%% game is over if opponent wins
.
%.......................................
% make_move
%.......................................
% requests next move from human/computer,
% then applies that move to the given board
%
make_move(P, B) :-
player(P, Type), % recuperation du Type du joueur P (human ou computer)
make_move2(Type, P, B, B2), % demande d'un coup dans une nouvelle board
retract( board(_) ), % remplacement de la board precedente
asserta( board(B2) ) % par la nouvelle board
.
% Demande d'un coup a un humain
make_move2(human, P, B, B2) :-
nl,
nl,
write('Player '),
write(P),
write(' move? '),
read(S),
blank_mark(E), % definition de E a la valeur de la blank_mark (voir les predicats, blank_mark = 'e')
square(B, S, E), % verification de la disponibilite de la case demandee (on regarde si elle contient la blank_mark)
player_mark(P, M), % recuperation de la marque M du joueur P
move(B, S, M, B2), ! % realisation du coup
.
% Fonction executee si la precedente echoue : l'utilisateur a entre un nombre invalide
make_move2(human, P, B, B2) :-
nl,
nl,
write('Error : Please select a numbered square.'), % Message d'erreur
make_move2(human,P,B,B2) % reexecution de la fonction precedente
.
% Demande d'un coup a l'ordinateur
make_move2(computer, P, B, B2) :-
nl,
nl,
write('Computer is thinking about next move...'),
player_mark(P, M), % recuperation de la marque M du joueur P
minimax(0, B, M, S, U), % calcul de la position S a jouer avec M
move(B,S,M,B2), % enregistrement du coup
nl,
nl,
write('Computer places '),
write(M),
write(' in square '),
write(S),
write('.')
.
%.......................................
% moves
%.......................................
% retrieves a list of available moves (empty squares) on a board.
%
moves(B,L) :-
not(win(B,x)), %%% if either player already won, then there are no available moves
not(win(B,o)),
blank_mark(E), % init de E a la valeur du blank_mark
findall(N, square(B,N,E), L), % remplit L avec toutes les positions N des cases vides (qui correspondent a square(B,N,E))
L \= []
.
%.......................................
% utility
%.......................................
% determines the value of a given board position
%
utility(B,U) :-
win(B,'x'), % si les 'x' gagnent
U = 1, % alors U vaudra 1
!
.
utility(B,U) :- % SINON (n'est execute que si la precedente a echoue)
win(B,'o'), % si les 'o' gagnent
U = (-1), % alors U vaudra -1
!
.
utility(B,U) :- % SINON (n'est execute que si la precedente a echoue)
U = 0 % U vaudra 0
.
%.......................................
% minimax
%.......................................
% The minimax algorithm always assumes an optimal opponent.
% For tic-tac-toe, optimal play will always result in a tie, so the algorithm is effectively playing not-to-lose.
% For the opening move against an optimal player, the best minimax can ever hope for is a tie.
% So, technically speaking, any opening move is acceptable.
% Save the user the trouble of waiting for the computer to search the entire minimax tree
% by simply selecting a random square.
% On connait D : profondeur de recherche
% On connait B : board de recherche
% On connait M : mark du joueur ('x' ou 'o')
% On cherche a determiner S, la meilleure position a jouer
% On cherche a determiner U, la meilleure evaluation qu'on a trouve, celle qui correspond a S
minimax(D,[E,E,E, E,E,E, E,E,E],M,S,U) :-
blank_mark(E), % Si la board est vide (toutes les cases matchent la blank_mark)
random_int_1n(9,S), % On choisit une position a jouer au hasard
!
.
minimax(D,B,M,S,U) :- % SINON (la board n'est pas vide)
D2 is D + 1,
moves(B,L), %%% get the list of available moves
!,
best(D2,B,M,L,S,U), %%% recursively determine the best available move
!
.
minimax(D,B,M,S,U) :- % SINON (there are no more available moves)
utility(B,U) % then the minimax value is the utility of the given board position
.
%.......................................
% best
%.......................................
% determines the best move in a given list of moves by recursively calling minimax
%
% if there is only one move left in the list ( [S1] )
best(D,B,M,[S1],S,U) :-
move(B,S1,M,B2), %%% apply that move to the board,
inverse_mark(M,M2), % recuperation de la mark de l'adversaire de M dans M2
!,
minimax(D,B2,M2,_S,U), %%% then recursively search for the utility value of that move. (???)
S = S1, !,
output_value(D,S,U),
!
.
% if there is more than one move in the list ( [S1|T] )
best(D,B,M,[S1|T],S,U) :-
move(B,S1,M,B2), %%% apply the first move (in the list) to the board,
inverse_mark(M,M2), % recuperation de la mark de l'adversaire de M dans M2
!,
minimax(D,B2,M2,_S,U1), %%% recursively search for the utility value of that move,
best(D,B,M,T,S2,U2), %%% determine the best move of the remaining moves,
output_value(D,S1,U1),
better(D,M,S1,U1,S2,U2,S,U) %%% and choose the better of the two moves (based on their respective utility values)
.
%.......................................
% better
%.......................................
% returns the better of two moves based on their respective utility values.
%
% if both moves have the same utility value, then one is chosen at random.
better(D,M,S1,U1,S2,U2, S,U) :-
maximizing(M), %%% if the player is maximizing
U1 > U2, %%% then greater is better.
S = S1,
U = U1,
!
.
better(D,M,S1,U1,S2,U2, S,U) :-
minimizing(M), %%% if the player is minimizing,
U1 < U2, %%% then lesser is better.
S = S1,
U = U1,
!
.
better(D,M,S1,U1,S2,U2, S,U) :-
U1 == U2, %%% if moves have equal utility,
random_int_1n(10,R), %%% then pick one of them at random
better2(D,R,M,S1,U1,S2,U2,S,U),
!
.
better(D,M,S1,U1,S2,U2, S,U) :- %%% otherwise, second move is better
S = S2,
U = U2,
!
.
%.......................................
% better2
%.......................................
% randomly selects two squares of the same utility value given a single probability
%
better2(D,R,M,S1,U1,S2,U2, S,U) :-
R < 6,
S = S1,
U = U1,
!
.
better2(D,R,M,S1,U1,S2,U2, S,U) :-
S = S2,
U = U2,
!
.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% OUTPUT
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
output_players :-
nl,
player(1, V1),
write('Player 1 is '), %%% either human or computer
write(V1),
nl,
player(2, V2),
write('Player 2 is '), %%% either human or computer
write(V2),
!
.
output_winner(B) :-
win(B,x),
write('X wins.'),
!
.
output_winner(B) :-
win(B,o),
write('O wins.'),
!
.
output_winner(B) :-
write('No winner.')
.
output_board(B) :-
nl,
nl,
output_square(B,1),
write('|'),
output_square(B,2),
write('|'),
output_square(B,3),
nl,
write('-----------'),
nl,
output_square(B,4),
write('|'),
output_square(B,5),
write('|'),
output_square(B,6),
nl,
write('-----------'),
nl,
output_square(B,7),
write('|'),
output_square(B,8),
write('|'),
output_square(B,9), !
.
output_board :-
board(B),
output_board(B), !
.
output_square(B,S) :-
square(B,S,M),
write(' '),
output_square2(S,M),
write(' '), !
.
output_square2(S, E) :-
blank_mark(E),
write(S), ! %%% if square is empty, output the square number
.
output_square2(S, M) :-
write(M), ! %%% if square is marked, output the mark
.
output_value(D,S,U) :-
D == 1,
nl,
write('Square '),
write(S),
write(', utility: '),
write(U), !
.
output_value(D,S,U) :-
true
.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% PSEUDO-RANDOM NUMBERS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%.......................................
% random_seed
%.......................................
% Initialize the random number generator...
% If no seed is provided, use the current time
%
random_seed :-
random_seed(_),
!
.
random_seed(N) :-
nonvar(N),
% Do nothing, SWI-Prolog does not support seeding the random number generator
!
.
random_seed(N) :-
var(N),
% Do nothing, SWI-Prolog does not support seeding the random number generator
!
.
/*****************************************
OTHER COMPILER SUPPORT
******************************************
arity_prolog___random_seed(N) :-
nonvar(N),
randomize(N),
!
.
arity_prolog___random_seed(N) :-
var(N),
time(time(Hour,Minute,Second,Tick)),
N is ( (Hour+1) * (Minute+1) * (Second+1) * (Tick+1)),
randomize(N),
!
.
******************************************/
%.......................................
% random_int_1n
%.......................................
% returns a random integer from 1 to N
%
random_int_1n(N, V) :-
V is random(N) + 1,
!
.
/*****************************************
OTHER COMPILER SUPPORT
******************************************
arity_prolog___random_int_1n(N, V) :-
R is random,
V2 is (R * N) - 0.5,
float_text(V2,V3,fixed(0)),
int_text(V4,V3),
V is V4 + 1,
!
.
******************************************/
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% LIST PROCESSING
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
member([V|T], V).
member([_|T], V) :- member(T,V).
append([], L, L).
append([H|T1], L2, [H|T3]) :- append(T1, L2, T3).
%.......................................
% set_item
%.......................................
% Given a list L, replace the item at position N with V
% return the new list in list L2
%
set_item(L, N, V, L2) :-
set_item2(L, N, V, 1, L2)
.
set_item2( [], N, V, A, L2) :-
N == -1,
L2 = []
.
set_item2( [_|T1], N, V, A, [V|T2] ) :-
A = N,
A1 is N + 1,
set_item2( T1, -1, V, A1, T2 )
.
set_item2( [H|T1], N, V, A, [H|T2] ) :-
A1 is A + 1,
set_item2( T1, N, V, A1, T2 )
.
%.......................................
% get_item
%.......................................
% Given a list L, retrieve the item at position N and return it as value V
%
get_item(L, N, V) :-
get_item2(L, N, 1, V)
.
get_item2( [], _N, _A, V) :-
V = [], !,
fail
.
get_item2( [H|_T], N, A, V) :-
A = N,
V = H
.
get_item2( [_|T], N, A, V) :-
A1 is A + 1,
get_item2( T, N, A1, V)
.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% End of program
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%