-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgame_arena.py
2164 lines (1763 loc) · 80.8 KB
/
game_arena.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
'''
AI project by Bokhtiar Adil and Sadman Sakib
'''
import os
import sys
import pygame as pg
import time
WINDOW_HEIGHT = 800
WINDOW_WIDTH = 1000
GAME_NAME = TITLE = "VIKINGS_CHESS"
GAME_ICON = pg.image.load("images/vh.jpg")
MAIN_MENU_TOP_BUTTON_x = 400
MAIN_MENU_TOP_BUTTON_y = 400
BOARD_TOP = 200
BOARD_LEFT = 125
CELL_WIDTH = 50
CELL_HEIGHT = 50
PIECE_RADIUS = 20
VALID_MOVE_INDICATOR_RADIUS = 10
SETTINGS_TEXT_GAP_VERTICAL = 50
SETTINGS_TEXT_GAP_HORIZONTAL = 100
bg = (204, 102, 0)
bg2 = (40, 40, 40)
red = (255, 0, 0)
black = (0, 0, 0)
yellow = (255, 255, 1)
golden = (255, 215, 0)
white = (255, 255, 255)
pink_fuchsia = (255, 0, 255)
green_neon = (15, 255, 80)
green_dark = (2, 48, 32)
green_teal = (0, 128, 128)
blue_indigo = (63, 0, 255)
blue_zaffre = (8, 24, 168)
ATTACKER_PIECE_COLOR = pink_fuchsia
DEFENDER_PIECE_COLOR = green_teal
KING_PIECE_COLOR = golden
VALID_MOVE_INDICATOR_COLOR = green_neon
BORDER_COLOR = blue_zaffre
GAME_ICON_resized = pg.image.load("images/vh_resized.jpg")
click_snd = os.path.join("sounds", "click_1.wav")
move_snd_1 = os.path.join("sounds", "move_1.mp3")
kill_snd_1 = os.path.join("sounds", "kill_1.mp3")
win_snd_1 = os.path.join("sounds", "win_1.wav")
lose_snd_1 = os.path.join("sounds", "lose_1.wav")
clicked = False
def write_text(text, screen, position, color, font, new_window=True):
'''
This function writes the given text at the given position on given surface applying th e given color and font.
Parameters
----------
text : string
This string will be #printed.
screen : a pygame display or surface
The text wiil be written on this suface.
position : a pair of values e.g. (x,y)
The text wiil be written at this position.
color : rgb coolor code e.g. (255,255,255)
The text wiil be written in this color.
font : a pygame font (pg.font.SysFont)
The text wiil be written in this font.
new_window : a boolean value, optional
This parameter wiil determine whether the text wil be #printed in a new window or current window.
If the former, all current text and graphics on this surface will be overwritten with background color.
The default is True.
Returns
-------
None.
'''
if new_window:
screen.fill(bg2)
txtobj = font.render(text, True, (255, 255, 255))
txtrect = txtobj.get_rect()
txtrect.topleft = position
screen.blit(txtobj, txtrect)
class Custom_button:
'''
This class holds the ncessary part of a custom button operation.
'''
button_col = (26, 117, 255)
hover_col = red
click_col = (50, 150, 255)
text_col = yellow
def __init__(self, x, y, text, screen, font, width=200, height=70):
self.x = x
self.y = y
self.text = text
self.screen = screen
self.font = font
self.width = width
self.height = height
def draw_button(self):
global clicked
action = False
# get mouse position
pos = pg.mouse.get_pos()
# create pg Rect object for the button
button_rect = pg.Rect(self.x, self.y, self.width, self.height)
# check mouseover and clicked conditions
if button_rect.collidepoint(pos):
if pg.mouse.get_pressed()[0] == 1:
clicked = True
pg.draw.rect(self.screen, self.click_col, button_rect)
elif pg.mouse.get_pressed()[0] == 0 and clicked == True:
clicked = False
action = True
else:
pg.draw.rect(self.screen, self.hover_col, button_rect)
else:
pg.draw.rect(self.screen, self.button_col, button_rect)
# add text to button
text_img = self.font.render(self.text, True, self.text_col)
text_len = text_img.get_width()
self.screen.blit(text_img, (self.x + int(self.width / 2) -
int(text_len / 2), self.y + 15))
return action
class ChessBoard:
'''
This class contains all properties of a chess board.
Properties:
1. initial_pattern: this parameter holds the position of pieces at the start of the match.
2. rows: n(rows) on board
3. columns: n(columns) on board
4. cell_width: width of each cell on surface
5. cell_height: height of each cell on surface
6. screen: where the board will be #printed
7. restricted_cell: holds the (row, column) value of restricted cells
Methods:
1. draw_empty_board(): this method draws an empty board with no piece on given surface
2. initiate_board_pieces(): this method initiates all the sprite instances of different types of pieces
'''
def __init__(self, screen, board_size="large"):
# board size large means 11x11, small measn 9x9
self.initial_pattern11 = ["x..aaaaa..x",
".....a.....",
"...........",
"a....d....a",
"a...ddd...a",
"aa.ddcdd.aa",
"a...ddd...a",
"a....d....a",
"...........",
".....a.....",
"x..aaaaa..x"]
self.initial_pattern9 = ["x..aaa..x",
"....a....",
".........",
"a..ddd..a",
"aa.dcd.aa",
"a..ddd..a",
".........",
"....a....",
"x..aaa..x"]
if board_size == "large":
self.initial_pattern = self.initial_pattern11
else:
self.initial_pattern = self.initial_pattern9
self.rows = len(self.initial_pattern)
self.columns = len(self.initial_pattern[0])
self.cell_width = CELL_WIDTH
self.cell_height = CELL_HEIGHT
self.screen = screen
self.restricted_cells = [(0, 0), (0, self.columns-1), (int(self.rows/2), int(
self.columns/2)), (self.rows-1, 0), (self.rows-1, self.columns-1)]
def draw_empty_board(self):
'''
This method draws an empty board with no piece on given surface
Returns
-------
None.
'''
border_top = pg.Rect(BOARD_LEFT - 10, BOARD_TOP -
10, self.columns*CELL_WIDTH + 20, 10)
pg.draw.rect(self.screen, BORDER_COLOR, border_top)
border_down = pg.Rect(BOARD_LEFT - 10, BOARD_TOP +
self.rows*CELL_HEIGHT, self.columns*CELL_WIDTH + 20, 10)
pg.draw.rect(self.screen, BORDER_COLOR, border_down)
border_left = pg.Rect(BOARD_LEFT - 10, BOARD_TOP -
10, 10, self.rows*CELL_HEIGHT + 10)
pg.draw.rect(self.screen, BORDER_COLOR, border_left)
border_right = pg.Rect(BOARD_LEFT+self.columns*CELL_WIDTH,
BOARD_TOP - 10, 10, self.rows*CELL_HEIGHT + 10)
pg.draw.rect(self.screen, BORDER_COLOR, border_right)
color_flag = True
for row in range(self.rows):
write_text(str(row), self.screen, (BOARD_LEFT - 30, BOARD_TOP + row*CELL_HEIGHT +
PIECE_RADIUS), (255, 255, 255), pg.font.SysFont("Arial", 15), False)
write_text(str(row), self.screen, (BOARD_LEFT + row*CELL_WIDTH +
PIECE_RADIUS, BOARD_TOP - 30), (255, 255, 255), pg.font.SysFont("Arial", 15), False)
for column in range(self.columns):
cell_rect = pg.Rect(BOARD_LEFT + column * self.cell_width, BOARD_TOP +
row * self.cell_height, self.cell_width, self.cell_height)
if (row == 0 or row == self.rows-1) and (column == 0 or column == self.columns-1):
pg.draw.rect(self.screen, red, cell_rect)
elif row == int(self.rows / 2) and column == int(self.columns / 2):
pg.draw.rect(self.screen, blue_indigo, cell_rect)
elif color_flag:
pg.draw.rect(self.screen, white, cell_rect)
else:
pg.draw.rect(self.screen, black, cell_rect)
color_flag = not color_flag
def initiate_board_pieces(self):
'''
This method initiates all the sprite instances of different types of pieces
Returns
-------
None.
'''
att_cnt, def_cnt = 1, 1
# for more effective use, this dict maps piece ids and pieces -> {pid : piece}
global piece_pid_map
piece_pid_map = {}
for row in range(self.rows):
for column in range(self.columns):
if self.initial_pattern[row][column] == 'a':
pid = "a" + str(att_cnt)
AttackerPiece(pid, row, column)
att_cnt += 1
elif self.initial_pattern[row][column] == 'd':
pid = "d" + str(def_cnt)
DefenderPiece(pid, row, column)
def_cnt += 1
elif self.initial_pattern[row][column] == 'c':
pid = "k"
KingPiece(pid, row, column)
else:
pass
for piece in All_pieces:
piece_pid_map[piece.pid] = piece
class ChessPiece(pg.sprite.Sprite):
'''
This class contains information about each piece.
Properties:
1. pid: holds a unique id for currnet piece instance
2. row: holds the row index of current piece instance
3. column: holds the column index of current piece instance
4. center: center position of corresponding piece instance
Methods:
1. update_piece_position(row, column): if the corresponding piece instance is moved, this method updates row and column value of that piece.
'''
def __init__(self, pid, row, column):
pg.sprite.Sprite.__init__(self, self.groups)
self.pid = pid
self.row, self.column = (row, column)
self.center = (BOARD_LEFT + int(CELL_WIDTH / 2) + self.column*CELL_WIDTH,
BOARD_TOP + int(CELL_HEIGHT / 2) + self.row*CELL_HEIGHT)
def draw_piece(self, screen):
'''
Draws a piece on board.
Parameters
----------
screen : surface
Returns
-------
None.
'''
pg.draw.circle(screen, self.color, self.center, PIECE_RADIUS)
def update_piece_position(self, row, column):
'''
This updates the position of all pieces on board.
Parameters
----------
row : row number
column : column number
Returns
-------
None.
'''
self.row, self.column = (row, column)
self.center = (BOARD_LEFT + int(CELL_WIDTH / 2) + self.column*CELL_WIDTH,
BOARD_TOP + int(CELL_HEIGHT / 2) + self.row*CELL_HEIGHT)
class AttackerPiece(ChessPiece):
'''
This class holds information about attacker pieces. It's a child of ChessPiece class.
Properties:
1. color: a rgb color code. e.g. (255,255,255)
color of the attacker piece that will be drawn on board.
2. ptype: type of piece. values:
i. "a" means attacker
ii. "d" means defender
ii. "k" means king.
here it's "a".
3. permit_to_res_sp: a boolean value.
tells whether the current piece is allowed on a restricted cell or not. here it's false.
'''
def __init__(self, pid, row, column):
ChessPiece.__init__(self, pid, row, column)
pg.sprite.Sprite.__init__(self, self.groups)
self.color = ATTACKER_PIECE_COLOR
self.permit_to_res_sp = False
self.ptype = "a"
class DefenderPiece(ChessPiece):
'''
This class holds information about defender pieces. It's a child of ChessPiece class.
Properties:
1. color: a rgb color code. e.g. (255,255,255)
color of the attacker piece that will be drawn on board.
2. ptype: type of piece. values:
i. "a" means attacker
ii. "d" means defender
ii. "k" means king.
here it's "d".
3. permit_to_res_sp: a boolean value.
tells whether the current piece is allowed on a restricted cell or not. here it's false.
'''
def __init__(self, pid, row, column):
ChessPiece.__init__(self, pid, row, column)
pg.sprite.Sprite.__init__(self, self.groups)
self.color = DEFENDER_PIECE_COLOR
self.permit_to_res_sp = False
self.ptype = "d"
class KingPiece(DefenderPiece):
'''
This class holds information about attacker pieces. It's a child of DefenderPiece class.
Properties:
1. color: a rgb color code. e.g. (255,255,255)
color of the attacker piece that will be drawn on board.
2. ptype: type of piece. values:
i. "a" means attacker
ii. "d" means defender
ii. "k" means king.
here it's "k".
3. permit_to_res_sp: a boolean value.
tells whether the current piece is allowed on a restricted cell or not. here it's true.
'''
def __init__(self, pid, row, column):
DefenderPiece.__init__(self, pid, row, column)
pg.sprite.Sprite.__init__(self, self.groups)
self.color = KING_PIECE_COLOR
self.permit_to_res_sp = True
self.ptype = "k"
def match_specific_global_data():
'''
This function declares and initiates all sprite groups.
Global Properties:
1. All_pieces: a srpite group containing all pieces.
2. Attacker_pieces: a srpite group containing all attacker pieces.
3. Defender_pieces: a srpite group containing all defender pieces.
4. King_pieces: a srpite group containing all king piece.
Returns
-------
None.
'''
global All_pieces, Attacker_pieces, Defender_pieces, King_pieces
All_pieces = pg.sprite.Group()
Attacker_pieces = pg.sprite.Group()
Defender_pieces = pg.sprite.Group()
King_pieces = pg.sprite.Group()
ChessPiece.groups = All_pieces
AttackerPiece.groups = All_pieces, Attacker_pieces
DefenderPiece.groups = All_pieces, Defender_pieces
KingPiece.groups = All_pieces, Defender_pieces, King_pieces
class Game_manager:
'''
This class handles all the events within the game.
Properties:
1. screen: a pygame display or surface.
holds the current screen where the game is played on.
2. board: a ChessBoard object.
this board is used in current game.
3. turn: a boolean value. default is True.
this value decides whose turn it is - attackers' or defenders'.
4. king_escape: a boolean value. dafult is false.
this variable tells whether the king is captured or not.
5. king_captured: a boolean value. default is false.
this variable tells whether the king escaped or not.
6. all_attackers_killed: a boolean value. default is false.
this variable tells if all attackers are killed or not.
7. finish: a boolean value. default is false.
this variable tells whether a match finishing condition is reached or not.
8. already_selected: a ChessPiece object, or any of it's child class object.
this varaible holds currenlty selected piece.
9. is_selected: a boolean value. default is false.
this variable tells whether any piece is selected or not.
10. valid_moves: a list of pair.
this list contains all the valid move indices- (row, column) of currently selected piece.
11. valid_moves_positions: a list of pair.
this list contains all the valid move pixel positions- (x_pos, y_pos) of currently selected piece.
12. current_board_status: a list of lists.
this holds current positions of all pieces i.e. current board pattern.
13. current_board_status_with_border: a list of lists.
this holds current positions of all pieces i.e. current board pattern along with border index.
(this is redundent I know, but, it's needed for avoiding complexity)
14. mode: 0 means p-vs-p, 1 means p-vs-ai
this variable holds game mode.
15. last_move: pair of pairs of indecies - ((prev_row, prev_col), (curr_row, curr_col))
this variable holds the 'from' and 'to' of last move.
16. board_size: "large" means 11x11, "small" means 9x9, default is "large"
this variable holds board sizes.
Methods:
1. select_piece(selected_piece):
to select a piece.
2. find_valid_moves():
finds valid moves of selected piece.
3. show_valid_moves():
draws the indicator of valid moves on board.
4. deselect():
deselects currently selected piece.
5. update_board_status():
updates board status after each move.
6. capture_check():
contains capture related logics.
7. king_capture_check():
contains caturing-king related logics.
8. escape_check():
contains king-escape related logics.
9. attackers_count_check():
counts currently unkilled attacker pieces.
10. match_finished():
performs necessary tasks when match ends.
11. mouse_click_analyzer(msx, msy):
analyzes current mouse click action and performs necessary functionalites.
12. turn_msg():
displays info about whose turn it is.
13. ai_move_manager(piece, row, column):
handles ai moves
'''
def __init__(self, screen, board, mode, board_size="large"):
self.screen = screen
self.board = board
self.turn = True
self.king_escaped = False
self.king_captured = False
self.all_attackers_killed = False
self.finish = False
self.already_selected = None
self.is_selected = False
self.valid_moves = []
self.valid_moves_positions = []
self.current_board_status = []
self.current_board_status_with_border = []
self.mode = mode
self.last_move = None
self.board_size = board_size
# initiating current_board_status and current_board_status_with_border.
# initially board is in initial_pattern
# appending top border row
border = []
for column in range(self.board.columns + 2):
border.append("=")
self.current_board_status_with_border.append(border)
# appending according to initial_pattern
for row in self.board.initial_pattern:
bordered_row = ["="] # to add a left border
one_row = []
for column in row:
one_row.append(column)
bordered_row.append(column)
self.current_board_status.append(one_row)
bordered_row.append("=") # to add a right border
self.current_board_status_with_border.append(bordered_row)
# appending bottom border row
self.current_board_status_with_border.append(border)
def select_piece(self, selected_piece):
'''
This method selects a piece.
Parameters
----------
selected_piece : a ChessPiece or it's child class object.
assigns this piece to already_selected variable.
Returns
-------
None.
'''
self.is_selected = True
self.already_selected = selected_piece
self.find_valid_moves()
def find_valid_moves(self):
'''
This method finds valid moves of selected piece.
Returns
-------
None.
'''
self.valid_moves = []
tempr = self.already_selected.row
tempc = self.already_selected.column
# finding valid moves in upwards direction
tempr -= 1
while tempr >= 0:
# stores current row and column
thispos = self.current_board_status[tempr][tempc]
# if finds any piece, no move left in this direction anymore
if thispos == "a" or thispos == "d" or thispos == "k" or (thispos == "x" and self.already_selected.ptype != "k"):
break
else:
# if selected piece is king, only one move per direction is allowed
if self.already_selected.ptype == "k":
if tempr < self.already_selected.row - 1 or tempr > self.already_selected.row + 1:
break
self.valid_moves.append((tempr, tempc))
else:
# "." means empty cell
if thispos == ".":
self.valid_moves.append((tempr, tempc))
tempr -= 1
tempr = self.already_selected.row
tempc = self.already_selected.column
# finding valid moves in downwards direction
tempr += 1
while tempr < self.board.rows:
# stores current row and column
thispos = self.current_board_status[tempr][tempc]
# if finds any piece, no move left in this direction anymore
if thispos == "a" or thispos == "d" or thispos == "k" or (thispos == "x" and self.already_selected.ptype != "k"):
break
else:
# if selected piece is king, only one move per direction is allowed
if self.already_selected.ptype == "k":
if tempr < self.already_selected.row - 1 or tempr > self.already_selected.row + 1:
break
self.valid_moves.append((tempr, tempc))
else:
# "." means empty cell
if thispos == ".":
self.valid_moves.append((tempr, tempc))
tempr += 1
tempr = self.already_selected.row
tempc = self.already_selected.column
# finding valid moves in left direction
tempc -= 1
while tempc >= 0:
# stores current row and column
thispos = self.current_board_status[tempr][tempc]
# if finds any piece, no move left in this direction anymore
if thispos == "a" or thispos == "d" or thispos == "k" or (thispos == "x" and self.already_selected.ptype != "k"):
break
else:
# if selected piece is king, only one move per direction is allowed
if self.already_selected.ptype == "k":
if tempc < self.already_selected.column - 1 or tempc > self.already_selected.column + 1:
break
self.valid_moves.append((tempr, tempc))
else:
# "." means empty cell
if thispos == ".":
self.valid_moves.append((tempr, tempc))
tempc -= 1
tempr = self.already_selected.row
tempc = self.already_selected.column
# finding valid moves in right direction
tempc += 1
while tempc < self.board.columns:
# stores current row and column
thispos = self.current_board_status[tempr][tempc]
# if finds any piece, no move left in this direction anymore
if thispos == "a" or thispos == "d" or thispos == "k" or (thispos == "x" and self.already_selected.ptype != "k"):
break
else:
# if selected piece is king, only one move per direction is allowed
if self.already_selected.ptype == "k":
if tempc < self.already_selected.column - 1 or tempc > self.already_selected.column + 1:
break
self.valid_moves.append((tempr, tempc))
else:
# "." means empty cell
if thispos == ".":
self.valid_moves.append((tempr, tempc))
tempc += 1
# for each (row, column) index of each valid move, corresponding pixel position is stored
for position in self.valid_moves:
self.valid_moves_positions.append((BOARD_LEFT + int(CELL_WIDTH / 2) + position[1]*CELL_WIDTH,
BOARD_TOP + int(CELL_HEIGHT / 2) + position[0]*CELL_HEIGHT))
def show_valid_moves(self):
'''
This method draws the indicator of valid moves on board.
Returns
-------
None.
'''
# iterating over valid moves positions and drawing them on board
for index in self.valid_moves_positions:
pg.draw.circle(self.screen, VALID_MOVE_INDICATOR_COLOR,
index, VALID_MOVE_INDICATOR_RADIUS)
def deselect(self):
'''
This method deselects currently selected piece.
Returns
-------
None.
'''
self.is_selected = False
self.already_selected = None
self.valid_moves = []
self.valid_moves_positions = []
def update_board_status(self):
'''
This method updates board status after each move.
Returns
-------
None.
'''
self.current_board_status = []
self.current_board_status_with_border = []
# adding top border row
border = []
for column in range(self.board.columns + 2):
border.append("=")
self.current_board_status_with_border.append(border)
# first setting all cells as empty cells, then making changes where necessary
for row in range(self.board.rows):
bordered_row = ["="] # left border
one_row = []
for column in range(self.board.columns):
one_row.append(".")
bordered_row.append(".")
if row == 0 or row == self.board.rows - 1:
one_row[0] = "x"
one_row[self.board.columns-1] = "x"
bordered_row[1] = "x"
bordered_row[self.board.columns] = "x"
self.current_board_status.append(one_row)
bordered_row.append("=") # right border
self.current_board_status_with_border.append(bordered_row)
# adding bottom border
self.current_board_status_with_border.append(border)
# according to each piece's positions, updating corresponding (row, column) value
for piece in All_pieces:
self.current_board_status[piece.row][piece.column] = piece.ptype
# adding an extra 1 because 0th row and 0th column is border
self.current_board_status_with_border[piece.row +
1][piece.column+1] = piece.ptype
# initial pattern set middle cell as empty cell. but, if it is actually an restricted cell.
# if it doesn't contain king, it's marked as "x'.
if self.current_board_status[int(self.board.rows/2)][int(self.board.columns/2)] != "k":
self.current_board_status[int(
self.board.rows/2)][int(self.board.columns/2)] = "x"
self.current_board_status_with_border[int(
self.board.rows/2)+1][int(self.board.columns/2)+1] = "x"
def capture_check(self):
'''
This method contains capture related logics.
Returns
-------
None.
'''
# storing current piece's type and index
ptype, prow, pcol = self.already_selected.ptype, self.already_selected.row + \
1, self.already_selected.column+1
# indices of sorrounding one hop cells and two hops cells.
sorroundings = [(prow, pcol+1), (prow, pcol-1),
(prow-1, pcol), (prow+1, pcol)]
two_hop_away = [(prow, pcol+2), (prow, pcol-2),
(prow-2, pcol), (prow+2, pcol)]
# iterating over each neighbour cells and finding out if the piece of this cell is captured or not
for pos, item in enumerate(sorroundings):
# currently selected cell's piece, if any
opp = self.current_board_status_with_border[item[0]][item[1]]
# if index is 1, which means it's right beside border, which means there's no two-hop cell in thi direction
# it may overflow the list index, so it will be set as empty cell instead to avoid error
try:
opp2 = self.current_board_status_with_border[two_hop_away[pos]
[0]][two_hop_away[pos][1]]
except:
opp2 = "."
# if next cell is empty or has same type of piece or has border, no capturing is possible
# if two hop cell is empty, then also no capturing is possible
if ptype == opp or ptype == "x" or ptype == "=" or opp == "." or opp2 == ".":
continue
elif opp == "k":
# king needs 4 enemies on 4 cardinal points to be captured. so, handled in another function.
self.king_capture_check(item[0], item[1])
# #print(self.king_captured)
elif ptype != opp:
# neghbour cell's piece is of different type
if ptype == "a" and (ptype == opp2 or opp2 == "x"):
# a-d-a or a-d-res_cell situation
for piece in All_pieces:
if piece.ptype == opp and piece.row == sorroundings[pos][0]-1 and piece.column == sorroundings[pos][1]-1:
pg.mixer.Sound.play(pg.mixer.Sound(kill_snd_1))
piece.kill()
self.update_board_status()
break
elif ptype != "a" and opp2 != "a" and opp2 != "=" and opp == "a":
# d-a-d or k-a-d or d-a-k or d-a-res_cell or k-a-res_cell situation
for piece in All_pieces:
if piece.ptype == opp and piece.row == sorroundings[pos][0]-1 and piece.column == sorroundings[pos][1]-1:
pg.mixer.Sound.play(pg.mixer.Sound(kill_snd_1))
piece.kill()
self.update_board_status()
break
if self.king_captured:
self.finish = True
pg.mixer.Sound.play(pg.mixer.Sound(lose_snd_1))
def king_capture_check(self, kingr, kingc):
'''
This method contains caturing-king related logics.
Parameters
----------
kingr : integer
row index of king piece.
kingc : integer
column index of king piece.
Returns
-------
None.
'''
# store all four neighbor cells' pieces
front = self.current_board_status_with_border[kingr][kingc+1]
back = self.current_board_status_with_border[kingr][kingc-1]
up = self.current_board_status_with_border[kingr-1][kingc]
down = self.current_board_status_with_border[kingr+1][kingc]
# if all four side has attackers or 3-attackers-one-bordercell situation occurs, king is captured
# all other possible combos are discarded
if front == "x" or back == "x" or up == "x" or down == "x":
return
elif front == "d" or back == "d" or up == "d" or down == "d":
return
elif front == "." or back == "." or up == "." or down == ".":
return
else:
self.king_captured = True
def escape_check(self):
'''
This method checks if the king has escaped or not.
Returns
-------
None.
'''
# (0,0), (0,n-1), (n-1,0), (n-1,n-1) cells are escape points for king in a n*n board
if self.current_board_status[0][0] == "k" or self.current_board_status[0][self.board.columns-1] == "k" or self.current_board_status[self.board.rows-1][0] == "k" or self.current_board_status[self.board.rows-1][self.board.columns-1] == "k":
self.king_escaped = True
self.finish = True
pg.mixer.Sound.play(pg.mixer.Sound(win_snd_1))
else:
self.king_escaped = False
def attackers_count_check(self):
'''
This method checks if all attackers are killed or not.
Returns
-------
None.
'''
# only way attackers would win is by capturing king, so it's not necessary to check defenders' count
# Attacker_pieces sprite group holds all attackers
if len(Attacker_pieces) == 0:
self.all_attackers_killed = True
self.finish = True
pg.mixer.Sound.play(pg.mixer.Sound(win_snd_1))
def match_finished(self):
'''
This method displays necessary messages when the match finishes.
Returns
-------
None.
'''
consolas = pg.font.SysFont("consolas", 22)
if self.king_captured:
if self.mode == 0:
write_text(">>> KING CAPTURED !! ATTACKERS WIN !!", self.screen, (20, BOARD_TOP - 80), white,
consolas, False)
else:
write_text(">>> KING CAPTURED !! AI WINS !!", self.screen, (20, BOARD_TOP - 80), white,
consolas, False)
elif self.king_escaped:
write_text(">>> KING ESCAPED !! DEFENDERS WIN !!", self.screen, (20, BOARD_TOP - 80), white,
consolas, False)
elif self.all_attackers_killed:
write_text(">>> ALL ATTACKERS DEAD !! DEFENDERS WIN !!", self.screen, (20, BOARD_TOP - 80), white,
consolas, False)
else:
pass
def mouse_click_analyzer(self, msx, msy):
'''
This method analyzes a mouse click event. This is the heart of Game_manager class.
Parameters
----------
msx : integer
the row index of mouse clicked position.
msy : integer
the column index of mouse clicked position.
Returns
-------
None.
'''
# if no piece is selected before and the player selects a piece, the valid moves of that piece is displayed
if not self.is_selected:
for piece in All_pieces:
# collidepoint was not working (dunno why...). so, instead, made a custom logic
# if mouse click position is within a distant of radius of piece from the center of so, it means it is clicked
# iterates over all pieces to find out which piece satiefies such condition
if (msx >= piece.center[0] - PIECE_RADIUS) and (msx < piece.center[0] + PIECE_RADIUS):
if (msy >= piece.center[1] - PIECE_RADIUS) and (msy < piece.center[1] + PIECE_RADIUS):
if (piece.ptype == "a" and self.turn) or (piece.ptype != "a" and not self.turn):
self.select_piece(piece)
break
elif (self.already_selected.ptype != "a" and self.turn) or (self.already_selected.ptype == "a" and not self.turn):
# opponent piece is selected, so previously selected piece will be deselected
self.deselect()
else:
# some piece was selected previously
# gonna check multiple scenerioes serially; if any meets requirement, 'done' flag will stop checking more
done = False
for piece in All_pieces:
if (msx >= piece.center[0] - PIECE_RADIUS) and (msx < piece.center[0] + PIECE_RADIUS):
if (msy >= piece.center[1] - PIECE_RADIUS) and (msy < piece.center[1] + PIECE_RADIUS):
done = True
if piece == self.already_selected:
# previously selected piece is selected again, so it will be deselected
self.deselect()
break
else:
# some other piece of same side is selected
# so previous one will be deselected and current will be selected
self.deselect()
if (piece.ptype == "a" and self.turn) or (piece.ptype != "a" and not self.turn):
self.select_piece(piece)
break
if not done: