Chess Game in Python
Chess Game in Python
import pygame
import time
import sys
## Creates a chess piece class that shows what team a piece is on, what type of
piece it is and whether or not it can be killed by another selected piece.
class Piece:
def __init__(self, team, type, image, killable=False):
self.team = team
self.type = type
self.killable = killable
self.image = image
## Creates instances of chess pieces, so far we got: pawn, king, rook and bishop
## The first parameter defines what team its on and the second, what type of piece
it is
bp = Piece('b', 'p', 'b_pawn.png')
wp = Piece('w', 'p', 'w_pawn.png')
bk = Piece('b', 'k', 'b_king.png')
wk = Piece('w', 'k', 'w_king.png')
br = Piece('b', 'r', 'b_rook.png')
wr = Piece('w', 'r', 'w_rook.png')
bb = Piece('b', 'b', 'b_bishop.png')
wb = Piece('w', 'b', 'w_bishop.png')
bq = Piece('b', 'q', 'b_queen.png')
wq = Piece('w', 'q', 'w_queen.png')
bkn = Piece('b', 'kn', 'b_knight.png')
wkn = Piece('w', 'kn', 'w_knight.png')
(0, 2): None, (1, 2): None, (2, 2): None, (3, 2): None,
(4, 2): None, (5, 2): None, (6, 2): None, (7, 2): None,
(0, 3): None, (1, 3): None, (2, 3): None, (3, 3): None,
(4, 3): None, (5, 3): None, (6, 3): None, (7, 3): None,
(0, 4): None, (1, 4): None, (2, 4): None, (3, 4): None,
(4, 4): None, (5, 4): None, (6, 4): None, (7, 4): None,
(0, 5): None, (1, 5): None, (2, 5): None, (3, 5): None,
(4, 5): None, (5, 5): None, (6, 5): None, (7, 5): None,
def create_board(board):
board[0] = [Piece('b', 'r', 'b_rook.png'), Piece('b', 'kn', 'b_knight.png'),
Piece('b', 'b', 'b_bishop.png'), \
Piece('b', 'q', 'b_queen.png'), Piece('b', 'k', 'b_king.png'),
Piece('b', 'b', 'b_bishop.png'), \
Piece('b', 'kn', 'b_knight.png'), Piece('b', 'r', 'b_rook.png')]
for i in range(8):
board[1][i] = Piece('b', 'p', 'b_pawn.png')
board[6][i] = Piece('w', 'p', 'w_pawn.png')
return board
## returns the input if the input is within the boundaries of the board
def on_board(position):
if position[0] > -1 and position[1] > -1 and position[0] < 8 and position[1] <
8:
return True
## returns a string that places the rows and columns of the board in a readable
manner
def convert_to_readable(board):
output = ''
for i in board:
for j in i:
try:
output += j.team + j.type + ', '
except:
output += j + ', '
output += '\n'
return output
## This takes in a piece object and its index then runs then checks where that
piece can move using separately defined functions for each type of piece.
def select_moves(piece, index, moves):
if check_team(moves, index):
if piece.type == 'p':
if piece.team == 'b':
return highlight(pawn_moves_b(index))
else:
return highlight(pawn_moves_w(index))
if piece.type == 'k':
return highlight(king_moves(index))
if piece.type == 'r':
return highlight(rook_moves(index))
if piece.type == 'b':
return highlight(bishop_moves(index))
if piece.type == 'q':
return highlight(queen_moves(index))
if piece.type == 'kn':
return highlight(knight_moves(index))
## Basically, check black and white pawns separately and checks the square above
them. If its free that space gets an "x" and if it is occupied by a piece of the
opposite team then that piece becomes killable.
def pawn_moves_b(index):
if index[0] == 1:
if board[index[0] + 2][index[1]] == ' ' and board[index[0] + 1][index[1]]
== ' ':
board[index[0] + 2][index[1]] = 'x '
bottom3 = [[index[0] + 1, index[1] + i] for i in range(-1, 2)]
def pawn_moves_w(index):
if index[0] == 6:
if board[index[0] - 2][index[1]] == ' ' and board[index[0] - 1][index[1]]
== ' ':
board[index[0] - 2][index[1]] = 'x '
top3 = [[index[0] - 1, index[1] + i] for i in range(-1, 2)]
## This just checks a 3x3 tile surrounding the king. Empty spots get an "x" and
pieces of the opposite team become killable.
def king_moves(index):
for y in range(3):
for x in range(3):
if on_board((index[0] - 1 + y, index[1] - 1 + x)):
if board[index[0] - 1 + y][index[1] - 1 + x] == ' ':
board[index[0] - 1 + y][index[1] - 1 + x] = 'x '
else:
if board[index[0] - 1 + y][index[1] - 1 + x].team !=
board[index[0]][index[1]].team:
board[index[0] - 1 + y][index[1] - 1 + x].killable = True
return board
## This creates 4 lists for up, down, left and right and checks all those spaces
for pieces of the opposite team. The list comprehension is pretty long so if you
don't get it just msg me.
def rook_moves(index):
cross = [[[index[0] + i, index[1]] for i in range(1, 8 - index[0])],
[[index[0] - i, index[1]] for i in range(1, index[0] + 1)],
[[index[0], index[1] + i] for i in range(1, 8 - index[1])],
[[index[0], index[1] - i] for i in range(1, index[1] + 1)]]
## Same as the rook but this time it creates 4 lists for the diagonal directions
and so the list comprehension is a little bit trickier.
def bishop_moves(index):
diagonals = [[[index[0] + i, index[1] + i] for i in range(1, 8)],
[[index[0] + i, index[1] - i] for i in range(1, 8)],
[[index[0] - i, index[1] + i] for i in range(1, 8)],
[[index[0] - i, index[1] - i] for i in range(1, 8)]]
## applies the rook moves to the board then the bishop moves because a queen is
basically a rook and bishop in the same position.
def queen_moves(index):
board = rook_moves(index)
board = bishop_moves(index)
return board
## Checks a 5x5 grid around the piece and uses pythagoras to see if if a move is
valid. Valid moves will be a distance of sqrt(5) from centre
def knight_moves(index):
for i in range(-2, 3):
for j in range(-2, 3):
if i ** 2 + j ** 2 == 5:
if on_board((index[0] + i, index[1] + j)):
if board[index[0] + i][index[1] + j] == ' ':
board[index[0] + i][index[1] + j] = 'x '
else:
if board[index[0] + i][index[1] + j].team !=
board[index[0]][index[1]].team:
board[index[0] + i][index[1] + j].killable = True
return board
WIDTH = 800
""" This is creating the window that we are playing on, it takes a tuple argument
which is the dimensions of the window so in this case 800 x 800px
"""
pygame.display.set_caption("Chess")
WHITE = (255, 255, 255)
GREY = (128, 128, 128)
YELLOW = (204, 204, 0)
BLUE = (50, 255, 255)
BLACK = (0, 0, 0)
class Node:
def __init__(self, row, col, width):
self.row = row
self.col = col
self.x = int(row * width)
self.y = int(col * width)
self.colour = WHITE
self.occupied = None
"""
For now it is drawing a rectangle but eventually we are going to need it
to use blit to draw the chess pieces instead
"""
def make_grid(rows, width):
grid = []
gap = WIDTH // rows
print(gap)
for i in range(rows):
grid.append([])
for j in range(rows):
node = Node(j, i, gap)
grid[i].append(node)
if (i+j)%2 ==1:
grid[i][j].colour = GREY
return grid
"""
This is creating the nodes thats are on the board(so the chess tiles)
I've put them into a 2d array which is identical to the dimesions of the chessboard
"""
"""
The nodes are all white so this we need to draw the grey lines that separate
all the chess tiles
from each other and that is what this function does"""
def remove_highlight(grid):
for i in range(len(grid)):
for j in range(len(grid[0])):
if (i+j)%2 == 0:
grid[i][j].colour = WHITE
else:
grid[i][j].colour = GREY
return grid
"""this takes in 2 co-ordinate parameters which you can get as the position of the
piece and then the position of the node it is moving to
you can get those co-ordinates using my old function for swap"""
create_board(board)
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
y, x = Find_Node(pos, WIDTH)
if selected == False:
try:
possible = select_moves((board[x][y]), (x,y), moves)
for positions in possible:
row, col = positions
grid[row][col].colour = BLUE
piece_to_move = x,y
selected = True
except:
piece_to_move = []
print('Can\'t select')
#print(piece_to_move)
else:
try:
if board[x][y].killable == True:
row, col = piece_to_move ## coords of original piece
board[x][y] = board[row][col]
board[row][col] = ' '
deselect()
remove_highlight(grid)
Do_Move((col, row), (y, x), WIN)
moves += 1
print(convert_to_readable(board))
else:
deselect()
remove_highlight(grid)
selected = False
print("Deselected")
except:
if board[x][y] == 'x ':
row, col = piece_to_move
board[x][y] = board[row][col]
board[row][col] = ' '
deselect()
remove_highlight(grid)
Do_Move((col, row), (y, x), WIN)
moves += 1
print(convert_to_readable(board))
else:
deselect()
remove_highlight(grid)
selected = False
print("Invalid move")
selected = False
main(WIN, WIDTH)