-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChessMain.py
More file actions
101 lines (85 loc) · 3.09 KB
/
Copy pathChessMain.py
File metadata and controls
101 lines (85 loc) · 3.09 KB
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
import pygame as p
import ChessEngine
# Width and height of the screen
WIDTH = HEIGHT = 512
DIMENSION = 8
SQ_SIZE = HEIGHT // DIMENSION
# Frames the game runs in
MAX_FPS = 15
IMAGES = {}
# Takes all chess piece images and adds them to the array
def loadImages():
pieces = ["wP","wR","wN","wB","wK","wQ","bP","bR","bN","bB","bK","bQ"]
for piece in pieces:
IMAGES[piece] = p.transform.scale(p.image.load("images/" + piece + ".png"), (SQ_SIZE,SQ_SIZE))
def main():
p.init()
screen = p.display.set_mode((WIDTH, HEIGHT))
clock = p.time.Clock()
screen.fill(p.Color("white"))
gs = ChessEngine.GameState()
validMade = gs.getValidMoves()
moveMade = False
validMoves = gs.getValidMoves()
loadImages()
running = True
sqSeleted = ()
playerClicks = []
# Loop that runs until the game is closed
while running:
for e in p.event.get():
if e.type == p.QUIT:
running = False
# Checks if the user has clicked on a square
elif e.type == p.MOUSEBUTTONDOWN:
location = p.mouse.get_pos()
col = location[0]//SQ_SIZE
row = location[1]//SQ_SIZE
# Checks if the same square has been selected twice
if sqSeleted == (row, col):
sqSeleted = ()
playerClicks = []
else:
sqSeleted = (row, col)
playerClicks.append(sqSeleted)
# If a second click is registered, makes a move to the board
if len(playerClicks) == 2:
move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board)
print(move.getChessNotation())
if move in validMoves:
gs.makeMove(move)
moveMade = True
sqSeleted = ()
playerClicks = []
# Key presses
# User can press the z key to undo the previous move
elif e.type == p.KEYDOWN:
if e.key == p.K_z:
gs.undoMove()
moveMade = True
if moveMade:
validMoves = gs.getValidMoves()
moveMade = False
drawGameState(screen, gs)
clock.tick(MAX_FPS)
p.display.flip()
# Drawing the game board and the individual pieces
def drawGameState(screen, gs):
drawBoard(screen)
drawPieces(screen,gs.board)
# Draw the squares where the pieces may lie
def drawBoard(screen):
colors = [p.Color("white"), p.Color("gray")]
for r in range(DIMENSION):
for c in range (DIMENSION):
color = colors[((r+c)%2)]
p.draw.rect(screen,color,p.Rect(c*SQ_SIZE,r*SQ_SIZE,SQ_SIZE,SQ_SIZE))
# Draw the pieces in top of the board
def drawPieces(screen, board):
for r in range(DIMENSION):
for c in range(DIMENSION):
piece = board[r][c]
if piece != "--":
screen.blit(IMAGES[piece], p.Rect(c*SQ_SIZE,r*SQ_SIZE,SQ_SIZE,SQ_SIZE))
if __name__ == "__main__":
main()