-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGames.py
541 lines (453 loc) · 17.8 KB
/
Games.py
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
from __future__ import annotations
import random
class GameState():
def __init__(self):
self.board = None
self.gameOver = False
pass
def eval(self) -> float:
"""Evaluates a gamestate and provides a score"""
pass
def getBaseline(self) -> GameState:
"""Returns a new gamestate with a random available move been played"""
pass
def isTerminal(self) -> bool:
"""Checks if the game is over"""
return self.gameOver
def getWinner(self) -> str:
"""Returns the winner of the game"""
pass
def getChildren(self) -> list[GameState]:
"""Returns list of gamestates / available moves"""
pass
def getMove(self) -> str:
"""Returns the last played move"""
pass
def getMemoization(self, isMax: bool) -> str:
"""Returns a unique string that represents the board"""
pass
def endGame(self):
"""Forces game over"""
self.gameOver = True
return self.gameOver
class TicTacToe(GameState):
def __init__(self, board=None, move=None, nDimensions: int = 3):
super().__init__()
if board is None:
self.board = [[' ' for _ in range(nDimensions)]
for _ in range(nDimensions)]
else:
self.board = board
self.k = nDimensions
self.move = move
def generateLines(n):
lines = []
for i in range(n):
# Horizontal lines
lines.append([(i, j) for j in range(n)])
# Vertical lines
lines.append([(j, i) for j in range(n)])
# Diagonal lines
lines.append([(i, i) for i in range(n)])
lines.append([(i, n - i - 1) for i in range(n)])
return lines
self.lines = generateLines(self.k)
def eval(self) -> float:
def count(player):
opponent = "O" if player == "X" else "X"
playerScore = 0
opponentScore = 0
for line in self.lines:
# Get count of both players per line
playerCount = sum([1 for x, y in line
if self.board[x][y] == player])
opponentCount = sum([1 for x, y in line
if self.board[x][y] == opponent])
if playerCount == self.k:
return 10 # Win
elif opponentCount == self.k:
return -10 # Lose
# About to win
if playerCount == self.k - 1 and opponentCount == 0:
playerScore += 2
# Opponent about to win / block them
if opponentCount == self.k - 1 and playerCount == 0:
opponentScore += 2
# Keep trying to fill the winnable lines
if playerCount >= 1 and opponentCount == 0:
playerScore += 1
if opponentCount >= 1 and playerCount == 0:
opponentScore += 1
return playerScore - opponentScore
return count("X") - count("O")
def getBaseline(self) -> GameState:
availableMoves = self.getChildren()
move = random.choice(availableMoves)
new_board = move.board
return TicTacToe(new_board, move.getMove(), self.k)
def isTerminal(self) -> bool:
"""Returns True if game is over"""
if super().isTerminal():
return True
for row in range(self.k):
if all(self.board[row][col] == self.board[row][0] and
self.board[row][0] != ' ' for col in range(self.k)):
return True
# Check columns
for col in range(self.k):
if all(self.board[row][col] == self.board[0][col] and
self.board[0][col] != ' ' for row in range(self.k)):
return True
# Check diagonals
if all(self.board[i][i] == self.board[0][0] and
self.board[0][0] != ' ' for i in range(self.k)):
return True
if all(self.board[i][self.k - i - 1] == self.board[0][self.k - 1] and
self.board[0][self.k - 1] != ' ' for i in range(self.k)):
return True
# Check for an empty cell
for row in self.board:
for cell in row:
if cell == ' ':
return False
# Board is full (tied)
return True
def getWinner(self):
# Check rows
for row in range(self.k):
if all(self.board[row][col] == self.board[row][0] and
self.board[row][0] != ' ' for col in range(self.k)):
return self.board[row][0]
# Check columns
for col in range(self.k):
if all(self.board[row][col] == self.board[0][col] and
self.board[0][col] != ' ' for row in range(self.k)):
return self.board[0][col]
# Check diagonals
if all(self.board[i][i] == self.board[0][0] and
self.board[0][0] != ' ' for i in range(self.k)):
return self.board[0][0]
if all(self.board[i][self.k - i - 1] == self.board[0][self.k - 1] and
self.board[0][self.k - 1] != ' ' for i in range(self.k)):
return self.board[0][self.k - 1]
return None
def getChildren(self):
children = []
for row in range(self.k):
for col in range(self.k):
if self.board[row][col] == ' ':
new_board = [row.copy() for row in self.board]
new_board[row][col] = 'X' if self.move == 'O' else 'O'
children.append(TicTacToe(new_board, new_board[row][col],
self.k))
return children
def getMove(self):
return self.move
def getMemoization(self, isMax: bool) -> str:
return str([j for sub in self.board for j in sub]) + " " + str(isMax)
class Nim(GameState):
def __init__(self, board=None, move=None, nDimensions: int = 3):
super().__init__()
if board is None:
val = 1
self.board = [val + _ * 2 for _ in range(nDimensions)]
else:
self.board = board
self.k = nDimensions
self.move = move
def eval(self) -> float:
if max(self.board) <= 1:
if sum(self.board) == 1:
return 10
if sum(self.board) == 0:
return -10
nimSum = 0
for pile in self.board:
nimSum ^= pile
return 1 if nimSum != 0 else -1
def getBaseline(self) -> Nim:
availableMoves = self.getChildren()
move = random.choice(availableMoves)
new_board = move.board
return TicTacToe(new_board, move.getMove(), self.k)
def isTerminal(self) -> bool:
if super().isTerminal():
return True
return all(pile == 0 for pile in self.board)
def getWinner(self) -> str:
if self.isTerminal():
return self.getMove()
else:
return None
def getChildren(self) -> list[int]:
children = []
for i, pile in enumerate(self.board):
if pile > 0:
# Must take a minimum of 1 stick
for j in range(1, pile + 1):
new_board = self.board.copy()
new_board[i] -= j
children.append(Nim(new_board,
new_board[i],
self.k))
return children
def getMove(self):
return self.move
def getMemoization(self, isMax: bool) -> str:
return str([_ for _ in self.board]) + " " + str(isMax)
class TigerAndDogs(GameState):
def __init__(
self, board=None, move=None,
nDimensions: int = 5, dogsKilled=0
):
super().__init__()
if board is None:
self.board = [[' ' for _ in range(nDimensions)]
for _ in range(nDimensions)]
for x in range(nDimensions):
for y in range(nDimensions):
if x == 0 or x == nDimensions-1:
self.board[x][y] = "O"
if y == 0 or y == nDimensions-1:
self.board[x][y] = "O"
self.board[int(nDimensions/2)][int(nDimensions/2)] = "X"
else:
self.board = board
self.k = nDimensions
self.move = move
self.tigerWin = False
self.dogsKilled = dogsKilled
def tigerSurrounded(self):
for row in range(self.k):
for col in range(self.k):
if self.board[row][col] == "X":
moves = self.getAvailableMoves(self.board, row, col)
if len(moves) == 0:
return True
return False
def eval(self) -> float:
"""ChatGPT helped in developing this evaluation function"""
def numberOfFreeDogs():
def dogsNotProtectingAnotherDog():
dogsPos = findPositions("O")
dogs_protecting = set()
directions = [(-1, 0), (1, 0), (0, -1), (0, 1),
(1, 1), (-1, 1), (-1, -1), (1, -1)]
for dog in dogsPos:
for dx, dy in directions:
row, col = dog[0] + dx, dog[1] + dy
if 0 <= row < self.k and 0 <= col < self.k:
if self.board[row][col] == "O":
for dx2, dy2 in directions:
row2, col2 = row + dx2, col + dy2
if 0 <= row2 < self.k and 0 <= col2 \
< self.k:
if self.board[row2][col2] == "X":
dogs_protecting.add(dog)
break
return len(dogsPos) - len(dogs_protecting)
return dogsNotProtectingAnotherDog()
# Dogs that can move without tiger killing friends
def findPositions(player: str):
out = []
for row in range(self.k):
for col in range(self.k):
if self.board[row][col] == player:
out.append((row, col,))
return out
def distanceToTiger():
def manhattanDistance(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
def sumDistToTiger():
dog_positions = findPositions("O")
tiger_positions = findPositions("X")
total_distance = 0
for dog in dog_positions:
min_distance = min(manhattanDistance(dog, tiger)
for tiger in tiger_positions)
total_distance += min_distance
return total_distance
return sumDistToTiger()
def score():
D = self.__getLivingDogs()
T = self.__getLivingTigers()
S = int(self.tigerSurrounded())
A = numberOfFreeDogs()
DT = distanceToTiger()
w_D = 1
w_T = 1
w_S = 10
w_A = 0.5
w_DT = -0.5
evaluation_score = w_D * D - w_T * T - w_S * S + \
w_A * A + w_DT * DT
return evaluation_score
return score()
def getBaseline(self) -> Nim:
availableMoves = self.getChildren()
move = random.choice(availableMoves)
new_board = move.board
return TigerAndDogs(new_board, move.getMove(), self.k, self.dogsKilled)
def __getLivingDogs(self):
livingDogs = sum(1 for row in self.board
for cell in row if cell == "O")
return livingDogs
def __getLivingTigers(self):
livingTigers = sum(1 for row in self.board
for cell in row if cell == "X")
return livingTigers
def isTerminal(self) -> bool:
if super().isTerminal():
return True
# Dogs lose
livingDogs = self.__getLivingDogs()
if livingDogs <= self.k*3+1 - 6: # 6 dead dogs
self.tigerWin = True
return True
# Tiger loses
return self.tigerSurrounded()
def getWinner(self) -> str:
if self.isTerminal():
return "X" if self.tigerWin else "O"
else:
return None
def getAvailableMoves(self, board, x, y) -> list[tuple[int]]:
moves = []
# piece = board[x][y]
# if piece == "T":
for x_ in range(-1, 2):
for y_ in range(-1, 2):
if x+x_ >= self.k:
__x = self.k-1
elif x+x_ < 0:
__x = 0
else:
__x = x+x_
if y+y_ >= self.k:
__y = self.k-1
elif y+y_ < 0:
__y = 0
else:
__y = y+y_
if board[__x][__y] == " ":
# or (__x, __y,) == (x, y,):
moves.append((__x, __y,))
# elif piece == "D":
# pass
return moves
def __getLine(self, board, tigerPos, dogPos):
"""ChatGPT helped me solve getting the relative lines in this func"""
line = []
correspondingPositions = []
tigerX, tigerY = tigerPos
dogX, dogY = dogPos
dx = dogX - tigerX
# if x == 0 vertical
dy = dogY - tigerY
# if y == 0 horizontal
# if both !=, diagonal
# if x > 0, left-to-right diag
# if x < 0, right-to-left diag
if dx != 0 and dy != 0:
if dx < 0:
x, y = tigerX, tigerY
while x >= 0 and y >= 0:
x -= 1
y -= 1
while x < len(board) and y < len(board):
line.append(board[x][y])
correspondingPositions.append((x, y,))
x += 1
y += 1
elif dx > 0:
x, y = tigerX, tigerY
while x <= self.k-1 and y > 0:
x += 1
y -= 1
while 0 <= x < len(board) and 0 <= y < len(board):
line.append(board[x][y])
correspondingPositions.append((x, y,))
x -= 1
y += 1
elif dx == 0 and dy != 0:
x = tigerX
y = 0
while y < len(board):
line.append(board[x][y])
correspondingPositions.append((x, y,))
y += 1
elif dx != 0 and dy == 0:
x = 0
y = tigerY
while x < len(board):
line.append(board[x][y])
correspondingPositions.append((x, y,))
x += 1
return (line, correspondingPositions,)
def tigerKillDogs(self, board, toMove: tuple):
def killDogs(linePos):
dogsKilled = 0
line, pos = linePos
for i in range(1, len(line) - 1):
if line[i] == "X" \
and (line[i - 1], line[i + 1]) == ("O", "O"):
board[pos[i-1][0]][pos[i-1][1]] = " "
board[pos[i+1][0]][pos[i+1][1]] = " "
dogsKilled = 2
self.dogsKilled += 2
break
return dogsKilled
deadDogs = 0
x, y = toMove
for x_ in range(-1, 2):
for y_ in range(-1, 2):
if x+x_ >= self.k:
__x = self.k-1
elif x+x_ < 0:
__x = 0
else:
__x = x+x_
if y+y_ >= self.k:
__y = self.k-1
elif y+y_ < 0:
__y = 0
else:
__y = y+y_
if board[__x][__y] == "O":
linePos = self.__getLine(board, toMove, (__x, __y,))
line, pos = linePos
if not any(line[i] == line[i + 1] == "O" for i in
range(len(line) - 1)):
if sum(1 for x in line if x == "O") > 1:
deadDogs = killDogs(linePos)
return (board, deadDogs,)
def getChildren(self):
children = []
for row in range(self.k):
for col in range(self.k):
currMove = "O" if self.move == "X" else "X"
if self.board[row][col] == currMove:
for move in self.getAvailableMoves(
self.board, row, col
):
new_board = [row.copy() for row in self.board]
new_board[row][col] = " "
new_board[move[0]][move[1]] = currMove
if currMove == "X":
deadDogs = self.tigerKillDogs(
new_board, move)
new_board = [row.copy() for row in deadDogs[0]]
children.append(
TigerAndDogs(new_board, self.move, self.k,
deadDogs[1])
)
else:
children.append(
TigerAndDogs(new_board, self.move, self.k,
self.dogsKilled)
)
return children
def getMove(self):
return self.move
def getMemoization(self, isMax: bool) -> str:
return str([j for sub in self.board for j in sub]) + " " + str(isMax)