-
Notifications
You must be signed in to change notification settings - Fork 1
/
interface.py
1603 lines (1364 loc) · 66.9 KB
/
interface.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
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import sys
import tkinter as tk
from tkinter import messagebox, simpledialog
import numpy as np
import pygame
import engine
win = tk.Tk()
win.withdraw()
# Window Dimensions #
WIDTH = 1050
HEIGHT = 700
WINDOW_SIZE = (WIDTH, HEIGHT)
# Color Values #
WHITE = (255, 255, 255)
LIGHTGREY = (170, 170, 170)
GREY = (85, 85, 85)
DARKGREY = (50, 50, 50)
DARKER_GREY = (35, 35, 35)
BLACK = (0, 0, 0)
RED = (230, 30, 30)
DARKRED = (150, 0, 0)
GREEN = (30, 230, 30)
DARKGREEN = (0, 125, 0)
BLUE = (30, 30, 122)
CYAN = (30, 230, 230)
GOLD = (225, 185, 0)
DARKGOLD = (165, 125, 0)
# Component Colors #
BOARD_LAYOUT_BACKGROUND = DARKGREY
SCREEN_BACKGROUND = LIGHTGREY
FOREGROUND = WHITE
CELL_BORDER_COLOR = BLUE
EMPTY_CELL_COLOR = GREY
# Board Dimensions #
ROW_COUNT = 6
COLUMN_COUNT = 7
# Component Dimensions #
SQUARE_SIZE = 100
PIECE_RADIUS = int(SQUARE_SIZE / 2 - 5)
# Board Coordinates #
BOARD_BEGIN_X = 30
BOARD_BEGIN_Y = SQUARE_SIZE
BOARD_END_X = BOARD_BEGIN_X + (COLUMN_COUNT * SQUARE_SIZE)
BOARD_END_Y = BOARD_BEGIN_Y + (ROW_COUNT * SQUARE_SIZE)
BOARD_LAYOUT_END_X = BOARD_END_X + 2 * BOARD_BEGIN_X
# Board Dimensions #
BOARD_WIDTH = BOARD_BEGIN_X + COLUMN_COUNT * SQUARE_SIZE
BOARD_LENGTH = ROW_COUNT * SQUARE_SIZE
# Player Variables #
PIECE_COLORS = (GREY, RED, GREEN)
PLAYER1 = 1
PLAYER2 = 2
EMPTY_CELL = 0
# Game-Dependent Global Variables #
TURN = 1
GAME_OVER = False
PLAYER_SCORE = [0, 0, 0]
GAME_BOARD = [[]]
usePruning = True
useTranspositionTable = False
screen = pygame.display.set_mode(WINDOW_SIZE)
GAME_MODE = -1
gameInSession = False
moveMade = False
HEURISTIC_USED = 1
AI_PLAYS_FIRST = False # Set to true for AI to make the first move
nodeStack = []
minimaxCurrentMode = "MAX"
# Game Modes #
SINGLE_PLAYER = 1
TWO_PLAYERS = 2
WHO_PLAYS_FIRST = -2
MAIN_MENU = -1
# Developer Mode: facilitates debugging during GUI development
DEVMODE = False
class GameWindow:
def switch(self):
self.refreshGameWindow()
self.gameSession()
def setupGameWindow(self):
"""
Initializes the all components in the frame
"""
global GAME_BOARD
GAME_BOARD = self.initGameBoard(EMPTY_CELL)
pygame.display.set_caption('Smart Connect4 :)')
self.refreshGameWindow()
def refreshGameWindow(self):
"""
Refreshes the screen and all the components
"""
pygame.display.flip()
refreshBackground()
self.drawGameBoard()
self.drawGameWindowButtons()
self.drawGameWindowLabels()
###### Labels ######
def drawGameWindowLabels(self):
"""
Draws all labels on the screen
"""
titleFont = pygame.font.SysFont("Sans Serif", 40, False, True)
mainLabel = titleFont.render("Smart Connect4", True, WHITE)
screen.blit(mainLabel, (BOARD_LAYOUT_END_X + 20, 20))
if not GAME_OVER:
captionFont = pygame.font.SysFont("Arial", 15)
player1ScoreCaption = captionFont.render("Player1", True, BLACK)
player2ScoreCaption = captionFont.render("Player2", True, BLACK)
screen.blit(player1ScoreCaption, (BOARD_LAYOUT_END_X + 48, 210))
screen.blit(player2ScoreCaption, (BOARD_LAYOUT_END_X + 170, 210))
if GAME_MODE == SINGLE_PLAYER:
global statsPanelY
depthFont = pygame.font.SysFont("Serif", math.ceil(23 - len(str(engine.BOARD.getDepth())) / 4))
depthLabel = depthFont.render("k = " + str(engine.BOARD.getDepth()), True, BLACK)
tempWidth = WIDTH - (BOARD_LAYOUT_END_X + 10)
centerX = BOARD_LAYOUT_END_X + 10 + (tempWidth / 2 - depthLabel.get_width() / 2)
screen.blit(depthLabel, (centerX, 294))
statsPanelY = 320
if usePruning:
depthFont = pygame.font.SysFont("Arial", 16)
depthLabel = depthFont.render("Using alpha-beta pruning", True, GOLD)
centerX = BOARD_LAYOUT_END_X + 10 + (tempWidth / 2 - depthLabel.get_width() / 2)
screen.blit(depthLabel, (centerX, 320))
statsPanelY += 20
if useTranspositionTable:
depthFont = pygame.font.SysFont("Arial", 16)
depthLabel = depthFont.render("Using transposition table", True, DARKGREEN)
centerX = BOARD_LAYOUT_END_X + 10 + (tempWidth / 2 - depthLabel.get_width() / 2)
screen.blit(depthLabel, (centerX, statsPanelY))
statsPanelY += 20
else:
if PLAYER_SCORE[PLAYER1] == PLAYER_SCORE[PLAYER2]:
verdict = 'DRAW :)'
elif PLAYER_SCORE[PLAYER1] > PLAYER_SCORE[PLAYER2]:
verdict = 'Player 1 Wins!'
else:
verdict = 'Player 2 Wins!'
verdictFont = pygame.font.SysFont("Serif", 40)
verdictLabel = verdictFont.render(verdict, True, GOLD)
screen.blit(verdictLabel, (BOARD_BEGIN_X + BOARD_END_X / 3, BOARD_BEGIN_Y / 3))
self.refreshScores()
self.refreshStats()
def refreshScores(self):
"""
Refreshes the scoreboard
"""
if GAME_OVER:
scoreBoard_Y = BOARD_BEGIN_Y
else:
scoreBoard_Y = 120
pygame.draw.rect(screen, BLACK, (BOARD_LAYOUT_END_X + 9, scoreBoard_Y - 1, 117, 82), 0)
player1ScoreSlot = pygame.draw.rect(screen, BOARD_LAYOUT_BACKGROUND,
(BOARD_LAYOUT_END_X + 10, scoreBoard_Y, 115, 80))
pygame.draw.rect(screen, BLACK, (BOARD_LAYOUT_END_X + 134, scoreBoard_Y - 1, 117, 82), 0)
player2ScoreSlot = pygame.draw.rect(screen, BOARD_LAYOUT_BACKGROUND,
(BOARD_LAYOUT_END_X + 135, scoreBoard_Y, 115, 80))
scoreFont = pygame.font.SysFont("Sans Serif", 80)
player1ScoreCounter = scoreFont.render(str(PLAYER_SCORE[PLAYER1]), True, PIECE_COLORS[1])
player2ScoreCounter = scoreFont.render(str(PLAYER_SCORE[PLAYER2]), True, PIECE_COLORS[2])
player1ScoreLength = player2ScoreLength = 2.7
if PLAYER_SCORE[PLAYER1] > 0:
player1ScoreLength += math.log(PLAYER_SCORE[PLAYER1], 10)
if PLAYER_SCORE[PLAYER2] > 0:
player2ScoreLength += math.log(PLAYER_SCORE[PLAYER2], 10)
screen.blit(player1ScoreCounter,
(player1ScoreSlot.x + player1ScoreSlot.width / player1ScoreLength, scoreBoard_Y + 15))
screen.blit(player2ScoreCounter,
(player2ScoreSlot.x + player2ScoreSlot.width / player2ScoreLength, scoreBoard_Y + 15))
def mouseOverMainLabel(self):
return 20 <= pygame.mouse.get_pos()[1] <= 45 and 810 <= pygame.mouse.get_pos()[0] <= 1030
def refreshStats(self):
"""
Refreshes the analysis section
"""
global statsPanelY
if GAME_MODE == SINGLE_PLAYER:
if GAME_OVER:
statsPanelY = showStatsButton.y + showStatsButton.height + 5
pygame.draw.rect(
screen, BLACK,
(BOARD_LAYOUT_END_X + 9, statsPanelY + 5, WIDTH - BOARD_LAYOUT_END_X - 18, 267 + (370 - statsPanelY)),
0)
pygame.draw.rect(
screen, GREY,
(BOARD_LAYOUT_END_X + 10, statsPanelY + 6, WIDTH - BOARD_LAYOUT_END_X - 20, 265 + (370 - statsPanelY)))
###### Buttons ######
def drawGameWindowButtons(self):
"""
Draws all buttons on the screen
"""
global showStatsButton, contributorsButton, \
playAgainButton, settingsButton, homeButton
global settingsIcon, settingsIconAccent, homeIcon, homeIconAccent
settingsIcon = pygame.image.load('GUI/settings-icon.png').convert_alpha()
settingsIconAccent = pygame.image.load('GUI/settings-icon-accent.png').convert_alpha()
homeIcon = pygame.image.load('GUI/home-icon.png').convert_alpha()
homeIconAccent = pygame.image.load('GUI/home-icon-accent.png').convert_alpha()
contributorsButton = Button(
screen, color=LIGHTGREY,
x=BOARD_LAYOUT_END_X + 10, y=650,
width=WIDTH - BOARD_LAYOUT_END_X - 20, height=30, text="Contributors")
contributorsButton.draw(BLACK)
settingsButton = Button(window=screen, color=(82, 82, 82), x=WIDTH - 48, y=BOARD_BEGIN_Y - 38,
width=35, height=35)
homeButton = Button(window=screen, color=(79, 79, 79), x=WIDTH - 88, y=BOARD_BEGIN_Y - 38,
width=35, height=35)
self.reloadSettingsButton(settingsIcon)
self.reloadHomeButton(homeIcon)
showStatsButton_Y = 250
if GAME_OVER:
showStatsButton_Y = 330
playAgainButton = Button(
window=screen, color=GOLD, x=BOARD_LAYOUT_END_X + 10, y=BOARD_BEGIN_Y + 100,
width=WIDTH - BOARD_LAYOUT_END_X - 20, height=120, text="Play Again")
playAgainButton.draw()
if GAME_MODE == SINGLE_PLAYER:
if moveMade:
statsButtonColor = LIGHTGREY
else:
statsButtonColor = DARKGREY
showStatsButton = Button(
screen, color=statsButtonColor,
x=BOARD_LAYOUT_END_X + 10, y=showStatsButton_Y,
width=WIDTH - BOARD_LAYOUT_END_X - 20, height=30, text="Observe decision tree")
showStatsButton.draw(BLACK)
def reloadSettingsButton(self, icon):
settingsButton.draw()
screen.blit(icon, (settingsButton.x + 2, settingsButton.y + 2))
def reloadHomeButton(self, icon):
homeButton.draw()
screen.blit(icon, (homeButton.x + 2, homeButton.y + 2))
###### Game Board ######
def initGameBoard(self, initialCellValue):
"""
Initializes the game board with the value given.
:param initialCellValue: Value of initial cell value
:return: board list with all cells initialized to initialCellValue
"""
global GAME_BOARD
GAME_BOARD = np.full((ROW_COUNT, COLUMN_COUNT), initialCellValue)
return GAME_BOARD
def printGameBoard(self):
"""
Prints the game board to the terminal
"""
print('\n-\n' +
str(GAME_BOARD) +
'\n Player ' + str(TURN) + ' plays next')
def drawGameBoard(self):
"""
Draws the game board on the interface with the latest values in the board list
"""
pygame.draw.rect(screen, BLACK, (0, 0, BOARD_LAYOUT_END_X, HEIGHT), 0)
boardLayout = pygame.draw.rect(
screen, BOARD_LAYOUT_BACKGROUND, (0, 0, BOARD_LAYOUT_END_X - 1, HEIGHT))
gradientRect(screen, DARKER_GREY, DARKGREY, boardLayout)
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
col = BOARD_BEGIN_X + (c * SQUARE_SIZE)
row = BOARD_BEGIN_Y + (r * SQUARE_SIZE)
piece = GAME_BOARD[r][c]
pygame.draw.rect(
screen, CELL_BORDER_COLOR, (col, row, SQUARE_SIZE, SQUARE_SIZE))
pygame.draw.circle(
screen, PIECE_COLORS[piece], (int(col + SQUARE_SIZE / 2), int(row + SQUARE_SIZE / 2)), PIECE_RADIUS)
pygame.display.update()
def hoverPieceOverSlot(self):
"""
Hovers the piece over the game board with the corresponding player's piece color
"""
boardLayout = pygame.draw.rect(screen, BOARD_LAYOUT_BACKGROUND,
(0, BOARD_BEGIN_Y - SQUARE_SIZE, BOARD_WIDTH + SQUARE_SIZE / 2, SQUARE_SIZE))
gradientRect(screen, DARKER_GREY, DARKGREY, boardLayout)
posx = pygame.mouse.get_pos()[0]
if BOARD_BEGIN_X < posx < BOARD_END_X:
pygame.mouse.set_visible(False)
pygame.draw.circle(screen, PIECE_COLORS[TURN], (posx, int(SQUARE_SIZE / 2)), PIECE_RADIUS)
else:
pygame.mouse.set_visible(True)
def dropPiece(self, col, piece) -> tuple:
"""
Drops the given piece in the next available cell in slot 'col'
:param col: Column index where the piece will be dropped
:param piece: Value of the piece to be put in array.
:returns: tuple containing the row and column of piece position
"""
row = self.getNextOpenRow(col)
GAME_BOARD[row][col] = piece
return row, col
def hasEmptyCell(self, col) -> bool:
"""
Checks if current slot has an empty cell. Assumes col is within array limits
:param col: Column index representing the slot
:return: True if slot has an empty cell. False otherwise.
"""
return GAME_BOARD[0][col] == EMPTY_CELL
def getNextOpenRow(self, col):
"""
Gets the next available cell in the slot
:param col: Column index
:return: If exists, the row of the first available empty cell in the slot. None otherwise.
"""
for r in range(ROW_COUNT - 1, -1, -1):
if GAME_BOARD[r][col] == EMPTY_CELL:
return r
return None
def boardIsFull(self) -> bool:
"""
Checks if the board game is full
:return: True if the board list has no empty slots, False otherwise.
"""
for slot in range(COLUMN_COUNT):
if self.hasEmptyCell(slot):
return False
return True
def getBoardColumnFromPos(self, posx):
"""
Get the index of the board column corresponding to the given position
:param posx: Position in pixels
:return: If within board bounds, the index of corresponding column, None otherwise
"""
column = int(math.floor(posx / SQUARE_SIZE))
if 0 <= column < COLUMN_COUNT:
return column
return None
def buttonResponseToMouseEvent(self, event):
"""
Handles button behaviour in response to mouse events influencing them
"""
if event.type == pygame.MOUSEMOTION:
if GAME_MODE == SINGLE_PLAYER and showStatsButton.isOver(event.pos):
if moveMade and not GAME_OVER:
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
alterButtonAppearance(showStatsButton, WHITE, BLACK)
elif contributorsButton.isOver(event.pos):
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
alterButtonAppearance(contributorsButton, WHITE, BLACK)
elif settingsButton.isOver(event.pos):
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
self.reloadSettingsButton(settingsIconAccent)
elif homeButton.isOver(event.pos):
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
self.reloadHomeButton(homeIconAccent)
elif GAME_OVER and playAgainButton.isOver(event.pos):
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
alterButtonAppearance(
button=playAgainButton, color=GOLD, outlineColor=BLACK, hasGradBackground=True,
gradLeftColor=WHITE, gradRightColor=GOLD, fontSize=22)
elif self.mouseOverMainLabel():
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
else:
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)
if GAME_MODE == SINGLE_PLAYER:
if moveMade and not GAME_OVER:
alterButtonAppearance(showStatsButton, LIGHTGREY, BLACK)
else:
alterButtonAppearance(showStatsButton, DARKGREY, BLACK)
alterButtonAppearance(contributorsButton, LIGHTGREY, BLACK)
self.reloadSettingsButton(settingsIcon)
self.reloadHomeButton(homeIcon)
if GAME_OVER:
alterButtonAppearance(playAgainButton, GOLD, BLACK)
if event.type == pygame.MOUSEBUTTONDOWN:
if GAME_MODE == SINGLE_PLAYER and not GAME_OVER and showStatsButton.isOver(event.pos) and moveMade:
alterButtonAppearance(showStatsButton, CYAN, BLACK)
elif contributorsButton.isOver(event.pos):
alterButtonAppearance(contributorsButton, CYAN, BLACK)
elif GAME_OVER and playAgainButton.isOver(event.pos):
alterButtonAppearance(
button=playAgainButton, color=GOLD, outlineColor=BLACK, hasGradBackground=True,
gradLeftColor=GOLD, gradRightColor=CYAN)
elif self.mouseOverMainLabel() or homeButton.isOver(event.pos):
self.resetEverything()
mainMenu.setupMainMenu()
mainMenu.show()
elif settingsButton.isOver(event.pos):
settingsWindow = SettingsWindow()
settingsWindow.setupSettingsMenu()
settingsWindow.show()
if event.type == pygame.MOUSEBUTTONUP:
if GAME_MODE == SINGLE_PLAYER and not GAME_OVER and showStatsButton.isOver(event.pos) and moveMade:
alterButtonAppearance(showStatsButton, LIGHTGREY, BLACK)
treevisualizer = TreeVisualizer()
treevisualizer.switch()
elif contributorsButton.isOver(event.pos):
alterButtonAppearance(contributorsButton, LIGHTGREY, BLACK)
self.showContributors()
elif GAME_OVER and playAgainButton.isOver(event.pos):
alterButtonAppearance(
button=playAgainButton, color=GOLD, outlineColor=BLACK, hasGradBackground=True,
gradLeftColor=WHITE, gradRightColor=GOLD, fontSize=22)
self.resetEverything()
if DEVMODE:
pygame.draw.rect(screen, BLACK, (BOARD_LAYOUT_END_X + 20, 70, WIDTH - BOARD_LAYOUT_END_X - 40, 40))
pygame.mouse.set_visible(True)
titleFont = pygame.font.SysFont("Sans Serif", 20, False, True)
coordinates = titleFont.render(str(pygame.mouse.get_pos()), True, WHITE)
screen.blit(coordinates, (BOARD_LAYOUT_END_X + 100, 80))
def showContributors(self):
"""
Invoked at pressing the contributors button. Displays a message box Containing names and IDs of contributors
"""
messagebox.showinfo('Contributors', "6744 - Adham Mohamed Aly\n"
"6905 - Mohamed Farid Abdelaziz\n"
"7140 - Yousef Ashraf Kotp\n")
def gameSession(self):
"""
Runs the game session
"""
global GAME_OVER, TURN, GAME_BOARD, gameInSession, moveMade, AI_PLAYS_FIRST
gameInSession = True
nodeStack.clear()
while True:
if AI_PLAYS_FIRST and not moveMade:
switchTurn()
self.player2Play()
moveMade = True
pygame.display.update()
if not GAME_OVER:
self.hoverPieceOverSlot()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.buttonResponseToMouseEvent(event)
if not GAME_OVER and event.type == pygame.MOUSEBUTTONDOWN:
posx = event.pos[0] - BOARD_BEGIN_X
column = self.getBoardColumnFromPos(posx)
if column is not None:
if self.hasEmptyCell(column):
self.dropPiece(column, TURN)
self.computeScore()
switchTurn()
self.refreshGameWindow()
moveMade = True
if not self.boardIsFull():
self.player2Play()
if self.boardIsFull():
GAME_OVER = True
pygame.mouse.set_visible(True)
self.refreshGameWindow()
break
def player2Play(self):
if GAME_MODE == SINGLE_PLAYER:
self.computerPlay()
elif GAME_MODE == TWO_PLAYERS:
pass
def computerPlay(self):
global GAME_BOARD, parentState
for i in range(ROW_COUNT):
for j in range(COLUMN_COUNT):
GAME_BOARD[i][j] -= 1
flippedGameBoard = np.flip(m=GAME_BOARD, axis=0) # Flip about x-axis
numericState = engine.convertToNumber(flippedGameBoard)
boardState = engine.nextMove(alphaBetaPruning=usePruning, state=numericState, heuristic=HEURISTIC_USED)
flippedNewState = engine.convertToTwoDimensions(boardState)
newState = np.flip(m=flippedNewState, axis=0) # Flip about x-axis
for i in range(ROW_COUNT):
for j in range(COLUMN_COUNT):
GAME_BOARD[i][j] += 1
newState[i][j] += 1
newC = self.getNewMove(newState=newState, oldState=GAME_BOARD)
boardLayout = pygame.draw.rect(screen, BOARD_LAYOUT_BACKGROUND,
(0, BOARD_BEGIN_Y - SQUARE_SIZE, BOARD_WIDTH + SQUARE_SIZE / 2, SQUARE_SIZE))
for i in range(BOARD_BEGIN_X, math.ceil(BOARD_BEGIN_X + newC * SQUARE_SIZE + SQUARE_SIZE / 2), 2):
gradientRect(screen, DARKER_GREY, DARKGREY, boardLayout)
pygame.draw.circle(
screen, PIECE_COLORS[TURN], (i, int(SQUARE_SIZE / 2)), PIECE_RADIUS)
pygame.display.update()
self.refreshGameWindow()
self.hoverPieceOverSlot()
GAME_BOARD = newState
self.computeScore()
switchTurn()
self.refreshGameWindow()
def resetEverything(self):
"""
Resets everything back to default values
"""
global GAME_BOARD, PLAYER_SCORE, GAME_OVER, TURN, moveMade
PLAYER_SCORE = [0, 0, 0]
GAME_OVER = False
TURN = 1
moveMade = False
self.setupGameWindow()
def getNewMove(self, newState, oldState) -> int:
"""
:return: New move made by the AI
"""
for r in range(ROW_COUNT):
for c in range(COLUMN_COUNT):
if newState[r][c] != oldState[r][c]:
return c
def computeScore(self):
"""
Computes every player's score and stores it in the global PLAYER_SCORES list
:returns: values in PLAYER_SCORES list
"""
global PLAYER_SCORE
PLAYER_SCORE = [0, 0, 0]
for r in range(ROW_COUNT):
consecutive = 0
for c in range(COLUMN_COUNT):
consecutive += 1
if c > 0 and GAME_BOARD[r][c] != GAME_BOARD[r][c - 1]:
consecutive = 1
if consecutive >= 4:
PLAYER_SCORE[GAME_BOARD[r][c]] += 1
for c in range(COLUMN_COUNT):
consecutive = 0
for r in range(ROW_COUNT):
consecutive += 1
if r > 0 and GAME_BOARD[r][c] != GAME_BOARD[r - 1][c]:
consecutive = 1
if consecutive >= 4:
PLAYER_SCORE[GAME_BOARD[r][c]] += 1
for r in range(ROW_COUNT - 3):
for c in range(COLUMN_COUNT - 3):
if GAME_BOARD[r][c] == GAME_BOARD[r + 1][c + 1] \
== GAME_BOARD[r + 2][c + 2] == GAME_BOARD[r + 3][c + 3]:
PLAYER_SCORE[GAME_BOARD[r][c]] += 1
for r in range(ROW_COUNT - 3):
for c in range(COLUMN_COUNT - 1, 2, -1):
if GAME_BOARD[r][c] == GAME_BOARD[r + 1][c - 1] \
== GAME_BOARD[r + 2][c - 2] == GAME_BOARD[r + 3][c - 3]:
PLAYER_SCORE[GAME_BOARD[r][c]] += 1
return PLAYER_SCORE
def isWithinBounds(self, mat, r, c) -> bool:
"""
:param mat: 2D matrix to check in
:param r: current row
:param c: current column
:return: True if coordinates are within matrix bounds, False otherwise
"""
return 0 <= r <= len(mat) and 0 <= c <= len(mat[0])
class MainMenu:
def switch(self):
self.setupMainMenu()
self.show()
def show(self):
while GAME_MODE == MAIN_MENU:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.buttonResponseToMouseEvent(event)
if GAME_MODE == WHO_PLAYS_FIRST:
WhoPlaysFirstMenu().switch()
else:
startGameSession()
def setupMainMenu(self):
"""
Initializes the all components in the frame
"""
global GAME_MODE, gameInSession
GAME_MODE = MAIN_MENU
gameInSession = False
pygame.display.flip()
pygame.display.set_caption('Smart Connect4 :) - Main Menu')
self.refreshMainMenu()
def refreshMainMenu(self):
"""
Refreshes the screen and all the components
"""
pygame.display.flip()
refreshBackground(BLACK, GREY)
self.drawMainMenuButtons()
self.drawMainMenuLabels()
def drawMainMenuButtons(self):
global singlePlayerButton, multiPlayerButton, SettingsButton_MAINMENU
singlePlayerButton = Button(
window=screen, color=LIGHTGREY, x=WIDTH / 3, y=HEIGHT / 3, width=WIDTH / 3, height=HEIGHT / 6,
gradCore=True, coreLeftColor=GREEN, coreRightColor=BLUE, text='PLAY AGAINST AI')
multiPlayerButton = Button(
window=screen, color=LIGHTGREY, x=WIDTH / 3, y=HEIGHT / 3 + HEIGHT / 5, width=WIDTH / 3,
height=HEIGHT / 6,
gradCore=True, coreLeftColor=GREEN, coreRightColor=BLUE, text='TWO-PLAYERS')
SettingsButton_MAINMENU = Button(
window=screen, color=LIGHTGREY, x=WIDTH / 3, y=HEIGHT / 3 + HEIGHT / 2.5, width=WIDTH / 3,
height=HEIGHT / 6,
gradCore=True, coreLeftColor=GREEN, coreRightColor=BLUE, text='GAME SETTINGS')
singlePlayerButton.draw(BLACK, 2)
multiPlayerButton.draw(BLACK, 2)
SettingsButton_MAINMENU.draw(BLACK, 2)
def drawMainMenuLabels(self):
titleFont = pygame.font.SysFont("Sans Serif", 65, False, True)
mainLabel = titleFont.render("Welcome to Smart Connect4 :)", True, WHITE)
screen.blit(mainLabel, (WIDTH / 5, HEIGHT / 8))
def buttonResponseToMouseEvent(self, event):
"""
Handles button behaviour in response to mouse events influencing them
"""
if event.type == pygame.MOUSEMOTION:
if singlePlayerButton.isOver(event.pos):
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
alterButtonAppearance(singlePlayerButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=WHITE, gradRightColor=BLUE)
elif multiPlayerButton.isOver(event.pos):
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
alterButtonAppearance(multiPlayerButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=WHITE, gradRightColor=BLUE)
elif SettingsButton_MAINMENU.isOver(event.pos):
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
alterButtonAppearance(SettingsButton_MAINMENU, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=WHITE, gradRightColor=BLUE)
else:
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)
alterButtonAppearance(singlePlayerButton, LIGHTGREY, BLACK,
hasGradBackground=True, gradLeftColor=GREEN, gradRightColor=BLUE)
alterButtonAppearance(multiPlayerButton, LIGHTGREY, BLACK,
hasGradBackground=True, gradLeftColor=GREEN, gradRightColor=BLUE)
alterButtonAppearance(SettingsButton_MAINMENU, LIGHTGREY, BLACK,
hasGradBackground=True, gradLeftColor=GREEN, gradRightColor=BLUE)
if event.type == pygame.MOUSEBUTTONDOWN:
if singlePlayerButton.isOver(event.pos):
alterButtonAppearance(singlePlayerButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=GOLD, gradRightColor=BLUE)
elif multiPlayerButton.isOver(event.pos):
alterButtonAppearance(multiPlayerButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=GOLD, gradRightColor=BLUE)
elif SettingsButton_MAINMENU.isOver(event.pos):
alterButtonAppearance(SettingsButton_MAINMENU, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=GOLD, gradRightColor=BLUE)
if event.type == pygame.MOUSEBUTTONUP:
global GAME_MODE
if singlePlayerButton.isOver(event.pos):
alterButtonAppearance(singlePlayerButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=GREEN, gradRightColor=BLUE)
setGameMode(WHO_PLAYS_FIRST)
elif multiPlayerButton.isOver(event.pos):
alterButtonAppearance(multiPlayerButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=GREEN, gradRightColor=BLUE)
setGameMode(TWO_PLAYERS)
elif SettingsButton_MAINMENU.isOver(event.pos):
alterButtonAppearance(multiPlayerButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=GREEN, gradRightColor=BLUE)
settingsWindow = SettingsWindow()
settingsWindow.switch()
class WhoPlaysFirstMenu:
def switch(self):
self.setupWPFMenu()
self.show()
def show(self):
while GAME_MODE == WHO_PLAYS_FIRST:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.buttonResponseToMouseEvent(event)
startGameSession()
def setupWPFMenu(self):
"""
Initializes the all components in the frame
"""
pygame.display.flip()
pygame.display.set_caption('Smart Connect4 :) - Who Plays First?')
self.refreshWPFMenu()
def refreshWPFMenu(self):
"""
Refreshes the screen and all the components
"""
pygame.display.flip()
refreshBackground(BLACK, GREY)
self.drawWPFButtons()
self.drawWPFLabels()
def reloadBackButton(self, icon):
backButton.draw()
screen.blit(icon, (backButton.x + 2, backButton.y + 2))
def drawWPFButtons(self):
global playerFirstButton, computerFirstButton
global backButton, backIcon, backIconAccent
backIconAccent = pygame.image.load('GUI/back-icon.png').convert_alpha()
backIcon = pygame.image.load('GUI/back-icon-accent.png').convert_alpha()
backButton = Button(window=screen, color=(81, 81, 81), x=WIDTH - 70, y=20, width=52, height=52)
self.reloadBackButton(backIcon)
playerFirstButton = Button(
window=screen, color=LIGHTGREY, x=WIDTH / 2 - 220, y=HEIGHT / 2, width=200, height=HEIGHT / 6,
gradCore=True, coreLeftColor=GREEN, coreRightColor=BLUE, text='HUMAN')
computerFirstButton = Button(
window=screen, color=LIGHTGREY, x=WIDTH / 2 + 20, y=HEIGHT / 2, width=200,
height=HEIGHT / 6,
gradCore=True, coreLeftColor=GREEN, coreRightColor=BLUE, text='COMPUTER')
playerFirstButton.draw(BLACK, 2)
computerFirstButton.draw(BLACK, 2)
def drawWPFLabels(self):
titleFont = pygame.font.SysFont("Sans Serif", 65, True, True)
mainLabel = titleFont.render("Who Plays First ?", True, LIGHTGREY)
screen.blit(mainLabel, (WIDTH / 2 - mainLabel.get_width() / 2, HEIGHT / 3 - mainLabel.get_height() / 2))
def buttonResponseToMouseEvent(self, event):
"""
Handles button behaviour in response to mouse events influencing them
"""
if event.type == pygame.MOUSEMOTION:
if playerFirstButton.isOver(event.pos):
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
alterButtonAppearance(playerFirstButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=WHITE, gradRightColor=BLUE)
elif computerFirstButton.isOver(event.pos):
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
alterButtonAppearance(computerFirstButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=WHITE, gradRightColor=BLUE)
elif backButton.isOver(event.pos):
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
self.reloadBackButton(backIconAccent)
else:
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)
alterButtonAppearance(playerFirstButton, LIGHTGREY, BLACK,
hasGradBackground=True, gradLeftColor=GREEN, gradRightColor=BLUE)
alterButtonAppearance(computerFirstButton, LIGHTGREY, BLACK,
hasGradBackground=True, gradLeftColor=GREEN, gradRightColor=BLUE)
self.reloadBackButton(backIcon)
if event.type == pygame.MOUSEBUTTONDOWN:
if playerFirstButton.isOver(event.pos):
alterButtonAppearance(playerFirstButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=GOLD, gradRightColor=BLUE)
elif computerFirstButton.isOver(event.pos):
alterButtonAppearance(computerFirstButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=GOLD, gradRightColor=BLUE)
elif backButton.isOver(event.pos):
MainMenu().switch()
if event.type == pygame.MOUSEBUTTONUP:
global GAME_MODE, AI_PLAYS_FIRST
if playerFirstButton.isOver(event.pos):
alterButtonAppearance(playerFirstButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=GREEN, gradRightColor=BLUE)
AI_PLAYS_FIRST = False
setGameMode(SINGLE_PLAYER)
elif computerFirstButton.isOver(event.pos):
alterButtonAppearance(computerFirstButton, WHITE, BLACK,
hasGradBackground=True, gradLeftColor=GREEN, gradRightColor=BLUE)
AI_PLAYS_FIRST = True
setGameMode(SINGLE_PLAYER)
class TreeVisualizer:
def switch(self):
self.setupTreeVisualizer()
self.show()
def show(self):
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.buttonResponseToMouseEvent(event)
def setupTreeVisualizer(self):
global minimaxCurrentMode
minimaxCurrentMode = 'MAX'
pygame.display.flip()
pygame.display.set_caption('Smart Connect4 :) - Tree Visualizer')
self.refreshTreeVisualizer(rootNode=None)
def refreshTreeVisualizer(self, rootNode=None):
refreshBackground()
self.drawTreeNodes(rootNode)
self.drawTreeVisualizerButtons()
self.drawTreeVisualizerLabels()
self.drawMiniGameBoard()
pygame.display.update()
def drawTreeNodes(self, parent):
global parentNodeButton, rootNodeButton, child1Button, child2Button, child3Button, child4Button, child5Button, child6Button, child7Button
global root, child1, child2, child3, child4, child5, child6, child7
child1 = child2 = child3 = child4 = child5 = child6 = child7 = None
parentNodeButton = Button(window=screen, color=DARKGREY, x=WIDTH / 2 - 70, y=10, width=140, height=100,
text='BACK TO PARENT',
shape='ellipse')
parentNodeButton.draw(BLACK)
if parent is None:
root = engine.BOARD.lastState
nodeStack.append(root)
rootValue = engine.BOARD.getValueFromMap(engine.BOARD.lastState)
else:
root = nodeStack[-1]
rootValue = engine.BOARD.getValueFromMap(root)
rootNodeButton = Button(window=screen, color=LIGHTGREY, x=WIDTH / 2 - 70, y=parentNodeButton.y + 200, width=140,
height=100, text=str(rootValue),
shape='ellipse')
children = engine.BOARD.getChildrenFromMap(root)
color, txt = GREY, ''
if children is not None and len(children) >= 1:
child1 = children[0]
color, txt = self.styleNode(child1)
child1Button = Button(window=screen, color=color, x=40, y=rootNodeButton.y + 300, width=140, height=100,
text=txt, shape='ellipse')
color, txt = GREY, ''
if children is not None and len(children) >= 2:
child2 = children[1]
color, txt = self.styleNode(child2)
child2Button = Button(window=screen, color=color, x=180, y=rootNodeButton.y + 200, width=140, height=100,
text=txt, shape='ellipse')
color, txt = GREY, ''
if children is not None and len(children) >= 3:
child3 = children[2]
color, txt = self.styleNode(child3)
child3Button = Button(window=screen, color=color, x=320, y=rootNodeButton.y + 300, width=140, height=100,
text=txt, shape='ellipse')
color, txt = GREY, ''
if children is not None and len(children) >= 4:
child4 = children[3]
color, txt = self.styleNode(child4)
child4Button = Button(window=screen, color=color, x=460, y=rootNodeButton.y + 200, width=140, height=100,
text=txt, shape='ellipse')
color, txt = GREY, ''
if children is not None and len(children) >= 5:
child5 = children[4]
color, txt = self.styleNode(child5)
child5Button = Button(window=screen, color=color, x=600, y=rootNodeButton.y + 300, width=140, height=100,
text=txt, shape='ellipse')
color, txt = GREY, ''
if children is not None and len(children) >= 6:
child6 = children[5]
color, txt = self.styleNode(child6)
child6Button = Button(window=screen, color=color, x=740, y=rootNodeButton.y + 200, width=140, height=100,
text=txt, shape='ellipse')
color, txt = GREY, ''
if children is not None and len(children) >= 7:
child7 = children[6]
color, txt = self.styleNode(child7)
child7Button = Button(window=screen, color=color, x=880, y=rootNodeButton.y + 300, width=140, height=100,
text=txt, shape='ellipse')
pygame.draw.rect(screen, WHITE, (
rootNodeButton.x + rootNodeButton.width / 2, rootNodeButton.y + rootNodeButton.height + 10, 2, 80))
pygame.draw.rect(screen, WHITE,
(
rootNodeButton.x + rootNodeButton.width / 2,
parentNodeButton.y + parentNodeButton.height + 10,
2, 80))
horizontalRule = pygame.draw.rect(screen, WHITE,
(child1Button.x + child1Button.width / 2,
rootNodeButton.y + rootNodeButton.height + 50,
WIDTH - (child1Button.x + child1Button.width / 2)
- (WIDTH - (child7Button.x + child7Button.width / 2)), 2))
pygame.draw.rect(screen, WHITE, (child2Button.x + child2Button.width / 2, horizontalRule.y, 2, 40))
pygame.draw.rect(screen, WHITE, (child6Button.x + child6Button.width / 2, horizontalRule.y, 2, 40))
pygame.draw.rect(screen, WHITE,
(child1Button.x + child1Button.width / 2, horizontalRule.y, 2, 40 + child2Button.height))
pygame.draw.rect(screen, WHITE,
(child7Button.x + child7Button.width / 2, horizontalRule.y, 2, 40 + child2Button.height))
pygame.draw.rect(screen, WHITE,
(child3Button.x + child3Button.width / 2, horizontalRule.y, 2, 40 + child2Button.height))
pygame.draw.rect(screen, WHITE,
(child5Button.x + child5Button.width / 2, horizontalRule.y, 2, 40 + child2Button.height))
rootNodeButton.draw()
child1Button.draw()
child2Button.draw()
child3Button.draw()
child4Button.draw()
child5Button.draw()
child6Button.draw()
child7Button.draw()