-
Notifications
You must be signed in to change notification settings - Fork 0
/
chess.py
94 lines (72 loc) · 2.28 KB
/
chess.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
"""
Main class responsible for running the game.
"""
import sys
from ai import AI
from board import Board
import pygame
from utils import WIDTH, HEIGHT, WHITE
def main():
"""
The method where all the game logic is implemented.
:return: None
"""
global run
# checking the run argument, printing usage instructions if invalid
if len(sys.argv) != 2:
print(f"Usage: python {sys.argv[0]} <PVP/AI>")
exit(1)
player_type = sys.argv[1]
if player_type not in ['PVP', 'AI']:
print(f"Usage: python {sys.argv[0]} <PVP/AI>")
exit(2)
# setting up pygame related variables
FPS = 60
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
# instancing classes
board = Board()
ai = AI()
while run:
clock.tick(FPS)
pygame.display.set_caption(f'Chess - {"white" if board.turn == WHITE else "black"} moves')
# check if game end condition is met
if board.game_ended:
run = False
print(f'\n{"White" if board.turn == WHITE else "Black"} won!')
# drawing the board and pieces
board.draw_board(WINDOW)
for row in board.pieces:
for piece in row:
if piece is not None:
piece.draw(WINDOW)
# checking player type
if player_type == 'PVP':
player_event(board)
if player_type == 'AI':
# checks if it's the AI's turn and moves randomly if yes
if ai.is_turn(board):
ai.move_random_piece(board)
else:
player_event(board)
pygame.display.update()
def player_event(board):
"""
A method that implements a player's turn.
:param board: the current board
:return: None
"""
global run
for event in pygame.event.get():
# if the player closes the window
if event.type == pygame.QUIT:
run = False
print(f'{"White" if board.turn == WHITE else "Black"} lost!')
# gets move from player and processes it
if event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
board.process_input(position)
board.can_move()
if __name__ == '__main__':
run = True
main()