-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmp2.py
More file actions
393 lines (338 loc) · 12.5 KB
/
mp2.py
File metadata and controls
393 lines (338 loc) · 12.5 KB
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
"""
Gen-Tic-Tac-Toe Minimax Search with alpha/beta pruning
Uses a custom evaluation function for estimating utilities past a maximum depth
"""
import numpy as np
import random
import math
class GenGameBoard:
"""
Class responsible for representing the game board and game playing methods
"""
num_pruned = 0 # counts number of pruned branches due to alpha/beta
num1 = 0 # counts number of pruned branches due to reaching maximum utility
numm1 = 0 # counts number of pruned braches due to reaching minimum utility
MAX_DEPTH = 6 # max depth before applying evaluation function
depth = 0 # current depth within minimax search
def __init__(self, boardSize):
"""
Constructor method - initializes each position variable and the board size
"""
self.boardSize = boardSize # Holds the size of the board
self.marks = np.empty((boardSize, boardSize), dtype='str') # Holds the mark for each position
self.marks[:, :] = ' '
def printBoard(self):
"""
Prints the game board using current marks
"""
# Print column numbers
print(' ', end='')
for j in range(self.boardSize):
print(" " + str(j + 1), end='')
# Print rows with marks
print("")
for i in range(self.boardSize):
# Print line separating the row
print(" ", end='')
for j in range(self.boardSize):
print("--", end='')
print("-")
# Print row number
print(i + 1, end='')
# Print marks on self row
for j in range(self.boardSize):
print("|" + self.marks[i][j], end='')
print("|")
# Print line separating the last row
print(" ", end='')
for j in range(self.boardSize):
print("--", end='')
print("-")
def makeMove(self, row, col, mark):
"""
Attempts to make a move given the row,col and mark
If move cannot be made, returns False and prints a message if mark is 'X'
Otherwise, returns True
"""
possible = False # Variable to hold the return value
if row == -1 and col == -1:
return False
# Change the row,col entries to array indexes
row = row - 1
col = col - 1
if row < 0 or row >= self.boardSize or col < 0 or col >= self.boardSize:
print("Not a valid row or column!")
return False
# Check row and col, and make sure space is empty
# If empty, set the position to the mark and change possible to True
if self.marks[row][col] == ' ':
self.marks[row][col] = mark
possible = True
# Print the message to the player if the move was not possible
if not possible and mark == 'X':
print("\nThis position is already taken!")
return possible
def checkWin(self, mark):
"""
Determines whether a game winning condition exists
If so, returns True, and False otherwise
"""
won = False # Variable holding the return value
# Check wins by examining each combination of positions
# Check each row
for i in range(self.boardSize):
won = True
for j in range(self.boardSize):
if self.marks[i][j] != mark:
won = False
break
if won:
break
# Check each column
if not won:
for i in range(self.boardSize):
won = True
for j in range(self.boardSize):
if self.marks[j][i] != mark:
won = False
break
if won:
break
# Check first diagonal
if not won:
for i in range(self.boardSize):
won = True
if self.marks[i][i] != mark:
won = False
break
# Check second diagonal
if not won:
for i in range(self.boardSize):
won = True
if self.marks[self.boardSize - 1 - i][i] != mark:
won = False
break
return won
def noMoreMoves(self):
"""
Determines whether the board is full
If full, returns True, and False otherwise
"""
return (self.marks != ' ').all()
# TODO - self method should run minimax to determine the value of each move
# Then make best move for the computer by placing the mark in the best spot
def makeCompMove(self):
"""
# This code chooses a random computer move
# Make sure the move was possible, if not try again
row, col = -1, -1
while not self.makeMove(row, col, 'O'):
col = random.randint(1,boardSize)
row = random.randint(1,boardSize)
print("Computer chose: "+str(row)+","+str(col))
"""
# Make AI move
bestAction = self.alpha_beta_search()
self.makeMove(bestAction[0] + 1, bestAction[1] + 1, 'O')
def is_terminal(self):
"""
Determines if the current board state is a terminal state
"""
if self.noMoreMoves() or self.checkWin('X') or self.checkWin('O'):
return True
else:
return False
def get_est_utility(self):
"""
Implements an evaluation function to estimate the utility of current state
"""
assert not self.is_terminal()
points = 0
# Check each row
for i in range(self.boardSize):
num_o_in_row = 0
num_x_in_row = 0
for j in range(self.boardSize):
if self.marks[i][j] == 'O':
num_o_in_row = num_o_in_row + 1
elif self.marks[i][j] == 'X':
num_x_in_row = num_x_in_row + 1
points = points + 10 ** num_o_in_row - 10 ** num_x_in_row
# Check each column
for i in range(self.boardSize):
num_o_in_row = 0
num_x_in_row = 0
for j in range(self.boardSize):
if self.marks[j][i] == 'O':
num_o_in_row = num_o_in_row + 1
elif self.marks[j][i] == 'X':
num_x_in_row = num_x_in_row + 1
points = points + 10 ** num_o_in_row - 10 ** num_x_in_row
# Check main diagonal
num_o_in_row = 0
num_x_in_row = 0
for i in range(self.boardSize):
if self.marks[i][i] == 'O':
num_o_in_row = num_o_in_row + 1
elif self.marks[i][i] == 'X':
num_x_in_row = num_x_in_row + 1
points = points + 10 ** num_o_in_row - 10 ** num_x_in_row
# Check other diagonal
num_o_in_row = 0
num_x_in_row = 0
for i in range(self.boardSize):
if self.marks[self.boardSize - 1 - i][i] == 'O':
num_o_in_row = num_o_in_row + 1
elif self.marks[self.boardSize - 1 - i][i] == 'X':
num_x_in_row = num_x_in_row + 1
points = points + 10 ** num_o_in_row - 10 ** num_x_in_row
return points
def get_utility(self):
"""
Finds the utility of a terminal state
"""
assert self.is_terminal()
if self.checkWin('X'):
return -10 ** self.boardSize
elif self.checkWin('O'):
return 10 ** self.boardSize
else:
return 0
def get_actions(self):
'''Generates a list of possible moves'''
return np.argwhere(self.marks == ' ')
def alpha_beta_search(self):
"""
Go through all possible successor states and generate the max_value
return action (row,col) that gives the max
uses the backtracking method
"""
GenGameBoard.depth = 0
v, bestAction = self.max_value(-math.inf, math.inf)
# print('Depth:',GenGameBoard.depth)
return bestAction
def max_value(self, alpha, beta):
"""
Finds the action that gives highest minimax value for computer
Returns both best action and the resulting value
"""
# print('Depth:',GenGameBoard.depth)
if self.is_terminal():
return self.get_utility(), np.array([-1, -1])
if GenGameBoard.depth > GenGameBoard.MAX_DEPTH:
return self.get_est_utility(), np.array([-1, -1])
v = -math.inf
for action in self.get_actions():
GenGameBoard.depth = GenGameBoard.depth + 1
# current_marks = np.array(self.marks) # save current state, so it can be backtracked
# self.makeMove(action[0]+1, action[1]+1, 'O')
self.marks[action[0]][action[1]] = 'O'
minVal = self.min_value(alpha, beta)
GenGameBoard.depth = GenGameBoard.depth - 1
if (minVal > v):
v = minVal
bestAction = action
# v = max(v, self.min_value(alpha, beta))
# self.marks = current_marks # backtrack to prior state
self.marks[action[0]][action[1]] = ' '
if v >= 10 ** self.boardSize:
GenGameBoard.num1 = GenGameBoard.num1 + 1
return v, bestAction
if v >= beta:
GenGameBoard.num_pruned = GenGameBoard.num_pruned + 1
return v, bestAction
alpha = max(alpha, v)
return v, bestAction
def min_value(self, alpha, beta):
"""
Finds the action that gives lowest minimax value for computer
Returns the resulting value
"""
# print('Depth:',GenGameBoard.depth)
if self.is_terminal():
return self.get_utility()
if GenGameBoard.depth > GenGameBoard.MAX_DEPTH:
return self.get_est_utility()
v = math.inf
for action in self.get_actions():
GenGameBoard.depth = GenGameBoard.depth + 1
# current_marks = np.array(self.marks) # save current state, so it can be backtracked
# self.makeMove(action[0]+1, action[1]+1, 'X')
self.marks[action[0]][action[1]] = 'X'
v = min(v, self.max_value(alpha, beta)[0])
# self.marks = current_marks # backtrack to prior state
# self.makeMove(action[0]+1, action[1]+1, ' ')
self.marks[action[0]][action[1]] = ' '
GenGameBoard.depth = GenGameBoard.depth - 1
if v <= -(10 ** self.boardSize):
GenGameBoard.numm1 = GenGameBoard.numm1 + 1
return v
if v <= alpha:
GenGameBoard.num_pruned = GenGameBoard.num_pruned + 1
return v
beta = min(beta, v)
return v
###########################
### Program starts here ###
###########################
# Print out the header info
print("CLASS: Artificial Intelligence, Lewis University")
print("NAME: Scott Carrington")
# Define constants
LOST = 0
WON = 1
DRAW = 2
# wrongInput = False
# Get the board size from the user
boardSize = int(input("Please enter the size of the board n (e.g. n=3,4,5,...): "))
# Create the game board of the given size and print it
board = GenGameBoard(boardSize)
board.printBoard()
# Start the game loop
while True:
# *** Player's move ***
# Try to make the move and check if it was possible
# If not possible get col,row inputs from player
row, col = -1, -1
while not board.makeMove(row, col, 'X'):
print("Player's Move")
row, col = input("Choose your move (row, column): ").split(',')
row = int(row)
col = int(col)
# Display the board again
board.printBoard()
print()
print("Waiting for computer's move......")
print()
# Check for ending condition
# If game is over, check if player won and end the game
if board.checkWin('X'):
# Player won
result = WON
break
elif board.noMoreMoves():
# No moves left -> draw
result = DRAW
break
# *** Computer's move ***
board.makeCompMove()
# Print out the board again
board.printBoard()
# Check for ending condition
# If game is over, check if computer won and end the game
if board.checkWin('O'):
# Computer won
result = LOST
break
elif board.noMoreMoves():
# No moves left -> draw
result = DRAW
break
# Check the game result and print out the appropriate message
print("GAME OVER")
if result == WON:
print("You Won!")
elif result == LOST:
print("You Lost!")
else:
print("It was a draw!")