-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChessMain.py
More file actions
83 lines (66 loc) · 2.54 KB
/
ChessMain.py
File metadata and controls
83 lines (66 loc) · 2.54 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
import pygame as p
import ChessEngine
import sys
sys.setrecursionlimit(3000)
WIDTH = HIGHT = 512
DIMENSION = 8
SQ_SIZE = WIDTH // DIMENSION
MAX_FPS = 15
IMAGES = {}
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))
IMAGES['--'] = p.Surface((0, 0))
def main():
p.init()
screen = p.display.set_mode((WIDTH, HIGHT))
clock = p.time.Clock()
screen.fill(p.Color("white"))
gs = ChessEngine.GameState()
validMoves = gs.getValidMoves(False, ())
moveMade = False
loadImages()
running = True
sqSelected = ()
playerClicks = []
while running:
for e in p.event.get():
running = not e.type == p.QUIT
sqSelected, playerClicks, moveMade = mouseButtonDown(e, sqSelected, playerClicks, gs, validMoves, moveMade)
moveMade = gs.undoMove(e.type == p.KEYDOWN and e.key == p.K_z, moveMade)
if moveMade:
validMoves = gs.getValidMoves(moveMade, sqSelected)
moveMade = False
drawGameState(screen, gs)
clock.tick(MAX_FPS)
p.display.flip()
def mouseButtonDown(e, sqSelected, playerClicks, gs, validMoves, moveMade):
if e.type == p.MOUSEBUTTONDOWN:
location = p.mouse.get_pos()
col = location[0] // SQ_SIZE
row = location[1] // SQ_SIZE
if sqSelected == (row, col):
playerClicks = []
return (), playerClicks, moveMade
sqSelected = (row, col)
playerClicks.append(sqSelected)
if len(playerClicks) == 2:
move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board)
moveMade, sqSelected, playerClicks = gs.makeMove(move, validMoves, moveMade, sqSelected)
return sqSelected, playerClicks, moveMade
if sqSelected:
return sqSelected, playerClicks, moveMade
return (), [], moveMade
def drawGameState(screen, gs):
drawBoard(screen, gs.board)
def drawBoard(screen, board):
colors = [p.Color("white"), p.Color("grey")]
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))
piece = board[r][c]
screen.blit(IMAGES[piece], p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE * (not piece == '--'), SQ_SIZE * (not piece == '--')))
if __name__ == "__main__":
main()