-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOthello2022.py
589 lines (480 loc) · 22.6 KB
/
Othello2022.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
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
# Flippy (an Othello or Reversi clone)
# By Al Sweigart al@inventwithpython.com
# http://inventwithpython.com/pygame
# Released under a "Simplified BSD" license
# Based on the "reversi.py" code that originally appeared in "Invent
# Your Own Computer Games with Python", chapter 15:
# http://inventwithpython.com/chapter15.html
import random, sys, pygame, time, copy
from typing import ValuesView
from pygame.locals import *
FPS = 10 # frames per second to update the screen
WINDOWWIDTH = 640 # width of the program's window, in pixels
WINDOWHEIGHT = 480 # height in pixels
SPACESIZE = 50 # width & height of each space on the board, in pixels
BOARDWIDTH = 8 # how many columns of spaces on the game board
BOARDHEIGHT = 8 # how many rows of spaces on the game board
WHITE_TILE = 'WHITE_TILE' # an arbitrary but unique value
BLACK_TILE = 'BLACK_TILE' # an arbitrary but unique value
EMPTY_SPACE = 'EMPTY_SPACE' # an arbitrary but unique value
HINT_TILE = 'HINT_TILE' # an arbitrary but unique value
ANIMATIONSPEED = 25 # integer from 1 to 100, higher is faster animation
# Amount of space on the left & right side (XMARGIN) or above and below
# (YMARGIN) the game board, in pixels.
XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * SPACESIZE)) / 2)
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * SPACESIZE)) / 2)
# R G B
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
GREEN = ( 0, 155, 0)
BRIGHTBLUE = ( 0, 50, 255)
BROWN = (174, 94, 0)
TEXTBGCOLOR1 = BRIGHTBLUE
TEXTBGCOLOR2 = GREEN
GRIDLINECOLOR = BLACK
TEXTCOLOR = WHITE
HINTCOLOR = BROWN
def main():
global MAINCLOCK, DISPLAYSURF, FONT, BIGFONT, BGIMAGE
pygame.init()
MAINCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Flippy')
FONT = pygame.font.Font('freesansbold.ttf', 16)
BIGFONT = pygame.font.Font('freesansbold.ttf', 32)
# Set up the background image.
boardImage = pygame.image.load('flippyboard.png')
# Use smoothscale() to stretch the board image to fit the entire board:
boardImage = pygame.transform.smoothscale(boardImage, (BOARDWIDTH * SPACESIZE, BOARDHEIGHT * SPACESIZE))
boardImageRect = boardImage.get_rect()
boardImageRect.topleft = (XMARGIN, YMARGIN)
BGIMAGE = pygame.image.load('flippybackground.png')
# Use smoothscale() to stretch the background image to fit the entire window:
BGIMAGE = pygame.transform.smoothscale(BGIMAGE, (WINDOWWIDTH, WINDOWHEIGHT))
BGIMAGE.blit(boardImage, boardImageRect)
# Run the main game.
while True:
if runGame() == False:
break
def runGame():
# Plays a single game of reversi each time this function is called.
# Reset the board and game.
mainBoard = getNewBoard()
resetBoard(mainBoard)
showHints = False
# Draw the starting board and ask the player what color they want.
drawBoard(mainBoard)
playerTile, computerTile = enterPlayerTile()
turn = 'player' if playerTile == BLACK_TILE else 'computer'
# Make the Surface and Rect objects for the "New Game" and "Hints" buttons
newGameSurf = FONT.render('New Game', True, TEXTCOLOR, TEXTBGCOLOR2)
newGameRect = newGameSurf.get_rect()
newGameRect.topright = (WINDOWWIDTH - 8, 10)
hintsSurf = FONT.render('Hints', True, TEXTCOLOR, TEXTBGCOLOR2)
hintsRect = hintsSurf.get_rect()
hintsRect.topright = (WINDOWWIDTH - 8, 40)
while True: # main game loop
# Keep looping for player and computer's turns.
if turn == 'player':
# Player's turn:
if getValidMoves(mainBoard, playerTile) == []:
# If it's the player's turn but they
# can't move, then end the game.
break
movexy = None
while movexy == None:
# Keep looping until the player clicks on a valid space.
# Determine which board data structure to use for display.
if showHints:
boardToDraw = getBoardWithValidMoves(mainBoard, playerTile)
else:
boardToDraw = mainBoard
checkForQuit()
for event in pygame.event.get(): # event handling loop
if event.type == MOUSEBUTTONUP:
# Handle mouse click events
mousex, mousey = event.pos
if newGameRect.collidepoint( (mousex, mousey) ):
# Start a new game
return True
elif hintsRect.collidepoint( (mousex, mousey) ):
# Toggle hints mode
showHints = not showHints
# movexy is set to a two-item tuple XY coordinate, or None value
movexy = getSpaceClicked(mousex, mousey)
if movexy != None and not isValidMove(mainBoard, playerTile, movexy[0], movexy[1]):
movexy = None
# Draw the game board.
drawBoard(boardToDraw)
drawInfo(boardToDraw, playerTile, computerTile, turn)
# Draw the "New Game" and "Hints" buttons.
DISPLAYSURF.blit(newGameSurf, newGameRect)
DISPLAYSURF.blit(hintsSurf, hintsRect)
MAINCLOCK.tick(FPS)
pygame.display.update()
# Make the move and end the turn.
makeMove(mainBoard, playerTile, movexy[0], movexy[1], True)
if getValidMoves(mainBoard, computerTile) != []:
# Only set for the computer's turn if it can make a move.
turn = 'computer'
else:
# Computer's turn:
possible_moves = getValidMoves(mainBoard, computerTile)
if possible_moves == []:
# If it was set to be the computer's turn but
# they can't move, then end the game.
break
# Draw the board.
drawBoard(mainBoard)
drawInfo(mainBoard, playerTile, computerTile, turn)
# Draw the "New Game" and "Hints" buttons.
DISPLAYSURF.blit(newGameSurf, newGameRect)
DISPLAYSURF.blit(hintsSurf, hintsRect)
# Make it look like the computer is thinking by pausing a bit.
pauseUntil = time.time() + random.randint(5, 15) * 0.1
while time.time() < pauseUntil:
pygame.display.update()
# Make the move and end the turn.
x, y = getComputerMove(mainBoard, computerTile)
makeMove(mainBoard, computerTile, x, y, True)
if getValidMoves(mainBoard, playerTile) != []:
# Only set for the player's turn if they can make a move.
turn = 'player'
# Display the final score.
drawBoard(mainBoard)
scores = getScoreOfBoard(mainBoard)
# Determine the text of the message to display.
if scores[playerTile] > scores[computerTile]:
text = 'You beat the computer by %s points! Congratulations!' % \
(scores[playerTile] - scores[computerTile])
elif scores[playerTile] < scores[computerTile]:
text = 'You lost. The computer beat you by %s points.' % \
(scores[computerTile] - scores[playerTile])
else:
text = 'The game was a tie!'
textSurf = FONT.render(text, True, TEXTCOLOR, TEXTBGCOLOR1)
textRect = textSurf.get_rect()
textRect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2))
DISPLAYSURF.blit(textSurf, textRect)
# Display the "Play again?" text with Yes and No buttons.
text2Surf = BIGFONT.render('Play again?', True, TEXTCOLOR, TEXTBGCOLOR1)
text2Rect = text2Surf.get_rect()
text2Rect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2) + 50)
# Make "Yes" button.
yesSurf = BIGFONT.render('Yes', True, TEXTCOLOR, TEXTBGCOLOR1)
yesRect = yesSurf.get_rect()
yesRect.center = (int(WINDOWWIDTH / 2) - 60, int(WINDOWHEIGHT / 2) + 90)
# Make "No" button.
noSurf = BIGFONT.render('No', True, TEXTCOLOR, TEXTBGCOLOR1)
noRect = noSurf.get_rect()
noRect.center = (int(WINDOWWIDTH / 2) + 60, int(WINDOWHEIGHT / 2) + 90)
while True:
# Process events until the user clicks on Yes or No.
checkForQuit()
for event in pygame.event.get(): # event handling loop
if event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
if yesRect.collidepoint( (mousex, mousey) ):
return True
elif noRect.collidepoint( (mousex, mousey) ):
return False
DISPLAYSURF.blit(textSurf, textRect)
DISPLAYSURF.blit(text2Surf, text2Rect)
DISPLAYSURF.blit(yesSurf, yesRect)
DISPLAYSURF.blit(noSurf, noRect)
pygame.display.update()
MAINCLOCK.tick(FPS)
def translateBoardToPixelCoord(x, y):
return XMARGIN + x * SPACESIZE + int(SPACESIZE / 2), YMARGIN + y * SPACESIZE + int(SPACESIZE / 2)
def animateTileChange(tilesToFlip, tileColor, additionalTile):
# Draw the additional tile that was just laid down. (Otherwise we'd
# have to completely redraw the board & the board info.)
if tileColor == WHITE_TILE:
additionalTileColor = WHITE
else:
additionalTileColor = BLACK
additionalTileX, additionalTileY = translateBoardToPixelCoord(additionalTile[0], additionalTile[1])
pygame.draw.circle(DISPLAYSURF, additionalTileColor, (additionalTileX, additionalTileY), int(SPACESIZE / 2) - 4)
pygame.display.update()
for rgbValues in range(0, 255, int(ANIMATIONSPEED * 2.55)):
if rgbValues > 255:
rgbValues = 255
elif rgbValues < 0:
rgbValues = 0
if tileColor == WHITE_TILE:
color = tuple([rgbValues] * 3) # rgbValues goes from 0 to 255
elif tileColor == BLACK_TILE:
color = tuple([255 - rgbValues] * 3) # rgbValues goes from 255 to 0
for x, y in tilesToFlip:
centerx, centery = translateBoardToPixelCoord(x, y)
pygame.draw.circle(DISPLAYSURF, color, (centerx, centery), int(SPACESIZE / 2) - 4)
pygame.display.update()
MAINCLOCK.tick(FPS)
checkForQuit()
def drawBoard(board):
# Draw background of board.
DISPLAYSURF.blit(BGIMAGE, BGIMAGE.get_rect())
# Draw grid lines of the board.
for x in range(BOARDWIDTH + 1):
# Draw the horizontal lines.
startx = (x * SPACESIZE) + XMARGIN
starty = YMARGIN
endx = (x * SPACESIZE) + XMARGIN
endy = YMARGIN + (BOARDHEIGHT * SPACESIZE)
pygame.draw.line(DISPLAYSURF, GRIDLINECOLOR, (startx, starty), (endx, endy))
for y in range(BOARDHEIGHT + 1):
# Draw the vertical lines.
startx = XMARGIN
starty = (y * SPACESIZE) + YMARGIN
endx = XMARGIN + (BOARDWIDTH * SPACESIZE)
endy = (y * SPACESIZE) + YMARGIN
pygame.draw.line(DISPLAYSURF, GRIDLINECOLOR, (startx, starty), (endx, endy))
# Draw the black & white tiles or hint spots.
for x in range(BOARDWIDTH):
for y in range(BOARDHEIGHT):
centerx, centery = translateBoardToPixelCoord(x, y)
if board[x][y] == WHITE_TILE or board[x][y] == BLACK_TILE:
if board[x][y] == WHITE_TILE:
tileColor = WHITE
else:
tileColor = BLACK
pygame.draw.circle(DISPLAYSURF, tileColor, (centerx, centery), int(SPACESIZE / 2) - 4)
if board[x][y] == HINT_TILE:
pygame.draw.rect(DISPLAYSURF, HINTCOLOR, (centerx - 4, centery - 4, 8, 8))
def getSpaceClicked(mousex, mousey):
# Return a tuple of two integers of the board space coordinates where
# the mouse was clicked. (Or returns None not in any space.)
for x in range(BOARDWIDTH):
for y in range(BOARDHEIGHT):
if mousex > x * SPACESIZE + XMARGIN and \
mousex < (x + 1) * SPACESIZE + XMARGIN and \
mousey > y * SPACESIZE + YMARGIN and \
mousey < (y + 1) * SPACESIZE + YMARGIN:
return (x, y)
return None
def drawInfo(board, playerTile, computerTile, turn):
# Draws scores and whose turn it is at the bottom of the screen.
scores = getScoreOfBoard(board)
scoreSurf = FONT.render("Player Score: %s Computer Score: %s %s's Turn" % (str(scores[playerTile]), str(scores[computerTile]), turn.title()), True, TEXTCOLOR)
scoreRect = scoreSurf.get_rect()
scoreRect.bottomleft = (10, WINDOWHEIGHT - 5)
DISPLAYSURF.blit(scoreSurf, scoreRect)
def resetBoard(board):
# Blanks out the board it is passed, and sets up starting tiles.
for x in range(BOARDWIDTH):
for y in range(BOARDHEIGHT):
board[x][y] = EMPTY_SPACE
# Add starting pieces to the center
board[3][3] = WHITE_TILE
board[3][4] = BLACK_TILE
board[4][3] = BLACK_TILE
board[4][4] = WHITE_TILE
def getNewBoard():
# Creates a brand new, empty board data structure.
board = []
for i in range(BOARDWIDTH):
board.append([EMPTY_SPACE] * BOARDHEIGHT)
return board
def isValidMove(board, tile, xstart, ystart):
# Returns False if the player's move is invalid. If it is a valid
# move, returns a list of spaces of the captured pieces.
if board[xstart][ystart] != EMPTY_SPACE or not isOnBoard(xstart, ystart):
return False
board[xstart][ystart] = tile # temporarily set the tile on the board.
if tile == WHITE_TILE:
otherTile = BLACK_TILE
else:
otherTile = WHITE_TILE
tilesToFlip = []
# check each of the eight directions:
for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]:
x, y = xstart, ystart
x += xdirection
y += ydirection
if isOnBoard(x, y) and board[x][y] == otherTile:
# The piece belongs to the other player next to our piece.
x += xdirection
y += ydirection
if not isOnBoard(x, y):
continue
while board[x][y] == otherTile:
x += xdirection
y += ydirection
if not isOnBoard(x, y):
break # break out of while loop, continue in for loop
if not isOnBoard(x, y):
continue
if board[x][y] == tile:
# There are pieces to flip over. Go in the reverse
# direction until we reach the original space, noting all
# the tiles along the way.
while True:
x -= xdirection
y -= ydirection
if x == xstart and y == ystart:
break
tilesToFlip.append([x, y])
board[xstart][ystart] = EMPTY_SPACE # make space empty
if len(tilesToFlip) == 0: # If no tiles flipped, this move is invalid
return False
return tilesToFlip
def isOnBoard(x, y):
# Returns True if the coordinates are located on the board.
return x >= 0 and x < BOARDWIDTH and y >= 0 and y < BOARDHEIGHT
def getBoardWithValidMoves(board, tile):
# Returns a new board with hint markings.
dupeBoard = copy.deepcopy(board)
for x, y in getValidMoves(dupeBoard, tile):
dupeBoard[x][y] = HINT_TILE
return dupeBoard
def getValidMoves(board, tile):
# Returns a list of (x,y) tuples of all valid moves.
validMoves = []
for x in range(BOARDWIDTH):
for y in range(BOARDHEIGHT):
if isValidMove(board, tile, x, y):
validMoves.append((x, y))
return validMoves
def getScoreOfBoard(board):
# Determine the score by counting the tiles.
xscore = 0
oscore = 0
for x in range(BOARDWIDTH):
for y in range(BOARDHEIGHT):
if board[x][y] == WHITE_TILE:
xscore += 1
if board[x][y] == BLACK_TILE:
oscore += 1
return {WHITE_TILE:xscore, BLACK_TILE:oscore}
def enterPlayerTile():
# Draws the text and handles the mouse click events for letting
# the player choose which color they want to be. Returns
# [WHITE_TILE, BLACK_TILE] if the player chooses to be White,
# [BLACK_TILE, WHITE_TILE] if Black.
# Create the text.
textSurf = FONT.render('Do you want to be white or black?', True, TEXTCOLOR, TEXTBGCOLOR1)
textRect = textSurf.get_rect()
textRect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2))
xSurf = BIGFONT.render('White', True, TEXTCOLOR, TEXTBGCOLOR1)
xRect = xSurf.get_rect()
xRect.center = (int(WINDOWWIDTH / 2) - 60, int(WINDOWHEIGHT / 2) + 40)
oSurf = BIGFONT.render('Black', True, TEXTCOLOR, TEXTBGCOLOR1)
oRect = oSurf.get_rect()
oRect.center = (int(WINDOWWIDTH / 2) + 60, int(WINDOWHEIGHT / 2) + 40)
while True:
# Keep looping until the player has clicked on a color.
checkForQuit()
for event in pygame.event.get(): # event handling loop
if event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
if xRect.collidepoint( (mousex, mousey) ):
return [WHITE_TILE, BLACK_TILE]
elif oRect.collidepoint( (mousex, mousey) ):
return [BLACK_TILE, WHITE_TILE]
# Draw the screen.
DISPLAYSURF.blit(textSurf, textRect)
DISPLAYSURF.blit(xSurf, xRect)
DISPLAYSURF.blit(oSurf, oRect)
pygame.display.update()
MAINCLOCK.tick(FPS)
def makeMove(board, tile, xstart, ystart, realMove=False):
# Place the tile on the board at xstart, ystart, and flip tiles
# Returns False if this is an invalid move, True if it is valid.
tilesToFlip = isValidMove(board, tile, xstart, ystart)
if tilesToFlip == False:
return False
board[xstart][ystart] = tile
if realMove:
animateTileChange(tilesToFlip, tile, (xstart, ystart))
for x, y in tilesToFlip:
board[x][y] = tile
return True
########################################
def opponent(tile):
return WHITE_TILE if tile == BLACK_TILE else BLACK_TILE
def hPuntuacio(board, computer_tile):
score = getScoreOfBoard(board) # Obté la puntuació del tauler
# Comprova qui som i retorna quants punts son nostres sobre el total de punts obtinguts
total = score[WHITE_TILE] + score[BLACK_TILE]
if computer_tile == WHITE_TILE:
return (score[WHITE_TILE] - score[BLACK_TILE])/total
else:
return (score[BLACK_TILE] - score[WHITE_TILE])/total
def hMoviments(board, computer_tile):
#Obté els moviments del jugador maximitzador
recompte_moviments_ia = len(getValidMoves(board, computer_tile))
#Moviments del jugador minimitzador
recompte_moviments_enemic = len(getValidMoves(board, BLACK_TILE if computer_tile == WHITE_TILE else WHITE_TILE))
total = recompte_moviments_ia + recompte_moviments_enemic # Suma del total
if total == 0:
return 0
else:
return (recompte_moviments_ia - recompte_moviments_enemic)/total
def hCantonades(board, computer_tile):
#Obté la mida del tauler
altura=len(board)-1
amplada=len(board[0])-1
#Genera array amb totes les cantonades
cantonades = [(0,0),(0,amplada),(altura,0),(altura,amplada)]
#Per cada cantonada, comprova de qui es la cantonada i assigna puntuacions segons qui és
puntuacio=0
for cantonada in cantonades:
if board[cantonada[0]][cantonada[1]] == computer_tile:
puntuacio+=0.25
elif board[cantonada[0]][cantonada[1]] == opponent(computer_tile):
puntuacio-=0.25
return puntuacio
def h(board, computer_tile):
#Calcula la hueristica
heuristicaPuntuacio = hPuntuacio(board, computer_tile)
heuristicaMoviments = hMoviments(board, computer_tile)
heuristicaCantonades = hCantonades(board, computer_tile)
#Ponderacio a 0.5 hCantonades
#Ponderacio a 0.25 hMoviments
#Ponderacio a 0.25 hPuntuacio
return (heuristicaMoviments+heuristicaPuntuacio)*0.25 + heuristicaCantonades*0.5
def minimax(board, depth, alfa, beta, tile, computer_tile):
# Si ens trobem al primer nivell de cerca parem
if depth == 0:
return h(board,computer_tile), None
# Generem els moviments valids
valid_move_list = getValidMoves(board, tile)
if valid_move_list == []:# Si no n'hi ha cap, parem
return h(board,computer_tile), None
condicio=None #Condicio generalitzada
# Si l'actual és l'ordinador ens trobem en cas maximitzador
if tile == computer_tile:
value = float("-inf") # Valor extrem negatiu
condicio = lambda a,b : a > b # condicio maximitzador
else:
value = float("inf") # Valor extrem positiu
condicio = lambda a,b : a < b # condicio minimitzador
# Algorisme
best_move = None # De moment no hi ha millor moviment
for move in valid_move_list: # Per cada moviment comprovem la seva millora
new_board = copy.deepcopy(board) # Fem una copia del tauler (sencera, no per ref)
makeMove(new_board, tile, move[0], move[1]) # Fem el moviment fictici
child_board_value, _ = minimax(new_board, depth-1, alfa, beta, BLACK_TILE if tile == WHITE_TILE else WHITE_TILE, computer_tile) # Crida recursiva
if condicio(child_board_value,value): # Si el camí actual ha estat millor l'assignem
value = child_board_value
best_move = move
if tile == computer_tile:#Actualitzacio del valor alfa/beta
alfa = value
else:
beta = value
if alfa >= beta: # Tall alfa-beta
break
return (value, best_move)
def getComputerMove(board, computerTile):
profunditat = 5 # Profunditat de la cerca
alfa = -profunditat # Valor extrem negatiu (profunditat * -1)
beta = profunditat # Valor extrem positiu (profunditat * 1)
_, best_move = minimax(board,profunditat,alfa, beta, computerTile, computerTile)
return best_move
def checkForQuit():
for event in pygame.event.get((QUIT, KEYUP)): # event handling loop
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()