In this tutorial, I want to show you How To Build A Chess Game In Python, which you can learn with the help of example source codes.
What Is Chess Game In Python?
Chess Game In Python is a two-player board game.
It is sometimes called “Western chess” or “international chess”.
To set it apart from games like “xiangqi” and “shogi,” which are similar but not the same.
Build Chess Game In Python Project Software Information
Project Name: | How To Build A Chess Game In Python |
Abstract: | The game of chess is played on a board by two people. It is like a war between two kingdoms. |
Language Used: | Python Programming Language |
Python Version: | 2.x or 3.x |
Database: | None |
Type: | GUI (Graphical User Interface) |
Developer: | Angel Jude Suarez |
About The Project
A chess game in python was developed using python programming language using pygame libraries.
This game project also includes a source code for free.
How To Code A Chess Game In Python?
Here are the steps on how to create a chess game in python. the game project has 5 classes to complete the chess game fully functional.
5 classes of the game:
Classes | Description |
main.py | This is the main class to start the game. |
chess.py | This is the main function of the game. |
game.py | This is the game design of the game. |
piece.py | This includes pieces that use in the game. |
utils.py | This includes a control to move the pieces. |
Main.py
from game import Game
if __name__=="__main__":
game = Game()
game.start_game()
game.py
import os
import pygame
from pygame.locals import *
from piece import Piece
from chess import Chess
from utils import Utils
class Game:
def __init__(self):
# screen dimensions
screen_width = 640
screen_height = 750
# flag to know if game menu has been showed
self.menu_showed = False
# flag to set game loop
self.running = True
# base folder for program resources
self.resources = "res"
# initialize game window
pygame.display.init()
# initialize font for text
pygame.font.init()
# create game window
self.screen = pygame.display.set_mode([screen_width, screen_height])
# title of window
window_title = "Chess Game By: Python For Free"
# set window caption
pygame.display.set_caption(window_title)
# update display
pygame.display.flip()
# set game clock
self.clock = pygame.time.Clock()
def start_game(self):
"""Function containing main game loop"""
# chess board offset
self.board_offset_x = 0
self.board_offset_y = 50
self.board_dimensions = (self.board_offset_x, self.board_offset_y)
# get location of chess board image
board_src = os.path.join(self.resources, "board.png")
# load the chess board image
self.board_img = pygame.image.load(board_src).convert()
# get the width of a chess board square
square_length = self.board_img.get_rect().width // 8
# initialize list that stores all places to put chess pieces on the board
self.board_locations = []
# calculate coordinates of the each square on the board
for x in range(0, 8):
self.board_locations.append([])
for y in range(0, 8):
self.board_locations[x].append([self.board_offset_x+(x*square_length),
self.board_offset_y+(y*square_length)])
# get location of image containing the chess pieces
pieces_src = os.path.join(self.resources, "pieces.png")
# create class object that handles the gameplay logic
self.chess = Chess(self.screen, pieces_src, self.board_locations, square_length)
# game loop
while self.running:
self.clock.tick(5)
# poll events
for event in pygame.event.get():
# get keys pressed
key_pressed = pygame.key.get_pressed()
# check if the game has been closed by the user
if event.type == pygame.QUIT or key_pressed[K_ESCAPE]:
# set flag to break out of the game loop
self.running = False
elif key_pressed[K_SPACE]:
self.chess.reset()
winner = self.chess.winner
if self.menu_showed == False:
self.menu()
elif len(winner) > 0:
self.declare_winner(winner)
else:
self.game()
# for testing mechanics of the game
#self.game()
#self.declare_winner(winner)
# update display
pygame.display.flip()
# update events
pygame.event.pump()
# call method to stop pygame
pygame.quit()
def menu(self):
"""method to show game menu"""
# background color
bg_color = (255, 255, 255)
# set background color
self.screen.fill(bg_color)
# black color
black_color = (0, 0, 0)
# coordinates for "Play" button
start_btn = pygame.Rect(270, 300, 100, 50)
# show play button
pygame.draw.rect(self.screen, black_color, start_btn)
# white color
white_color = (255, 255, 255)
# create fonts for texts
big_font = pygame.font.SysFont("Courier-new", 50)
small_font = pygame.font.SysFont("Courier-new", 20)
# create text to be shown on the game menu
welcome_text = big_font.render("Chess Game", False, black_color)
created_by = small_font.render("Created by Python For Free", True, black_color)
start_btn_label = small_font.render("Play", True, white_color)
# show welcome text
self.screen.blit(welcome_text,
((self.screen.get_width() - welcome_text.get_width()) // 2,
150))
# show credit text
self.screen.blit(created_by,
((self.screen.get_width() - created_by.get_width()) // 2,
self.screen.get_height() - created_by.get_height() - 100))
# show text on the Play button
self.screen.blit(start_btn_label,
((start_btn.x + (start_btn.width - start_btn_label.get_width()) // 2,
start_btn.y + (start_btn.height - start_btn_label.get_height()) // 2)))
# get pressed keys
key_pressed = pygame.key.get_pressed()
#
util = Utils()
# check if left mouse button was clicked
if util.left_click_event():
# call function to get mouse event
mouse_coords = util.get_mouse_event()
# check if "Play" button was clicked
if start_btn.collidepoint(mouse_coords[0], mouse_coords[1]):
# change button behavior as it is hovered
pygame.draw.rect(self.screen, white_color, start_btn, 3)
# change menu flag
self.menu_showed = True
# check if enter or return key was pressed
elif key_pressed[K_RETURN]:
self.menu_showed = True
def game(self):
# background color
color = (0,0,0)
# set backgound color
self.screen.fill(color)
# show the chess board
self.screen.blit(self.board_img, self.board_dimensions)
# call self.chess. something
self.chess.play_turn()
# draw pieces on the chess board
self.chess.draw_pieces()
def declare_winner(self, winner):
# background color
bg_color = (255, 255, 255)
# set background color
self.screen.fill(bg_color)
# black color
black_color = (0, 0, 0)
# coordinates for play again button
reset_btn = pygame.Rect(250, 300, 140, 50)
# show reset button
pygame.draw.rect(self.screen, black_color, reset_btn)
# white color
white_color = (255, 255, 255)
# create fonts for texts
big_font = pygame.font.SysFont("Courier-new", 50)
small_font = pygame.font.SysFont("Courier-new", 20)
# text to show winner
text = winner + " wins!"
winner_text = big_font.render(text, False, black_color)
# create text to be shown on the reset button
reset_label = "Play Again"
reset_btn_label = small_font.render(reset_label, True, white_color)
# show winner text
self.screen.blit(winner_text,
((self.screen.get_width() - winner_text.get_width()) // 2,
150))
# show text on the reset button
self.screen.blit(reset_btn_label,
((reset_btn.x + (reset_btn.width - reset_btn_label.get_width()) // 2,
reset_btn.y + (reset_btn.height - reset_btn_label.get_height()) // 2)))
# get pressed keys
key_pressed = pygame.key.get_pressed()
#
util = Utils()
# check if left mouse button was clicked
if util.left_click_event():
# call function to get mouse event
mouse_coords = util.get_mouse_event()
# check if reset button was clicked
if reset_btn.collidepoint(mouse_coords[0], mouse_coords[1]):
# change button behavior as it is hovered
pygame.draw.rect(self.screen, white_color, reset_btn, 3)
# change menu flag
self.menu_showed = False
# check if enter or return key was pressed
elif key_pressed[K_RETURN]:
self.menu_showed = False
# reset game
self.chess.reset()
# clear winner
self.chess.winner = ""
piece.py
import os
import pygame
class Piece(pygame.sprite.Sprite):
def __init__(self, filename, cols, rows):
pygame.sprite.Sprite.__init__(self)
self.pieces = {
"white_pawn": 5,
"white_knight": 3,
"white_bishop": 2,
"white_rook": 4,
"white_king": 0,
"white_queen": 1,
"black_pawn": 11,
"black_knight": 9,
"black_bishop": 8,
"black_rook": 10,
"black_king": 6,
"black_queen": 7
}
self.spritesheet = pygame.image.load(filename).convert_alpha()
self.cols = cols
self.rows = rows
self.cell_count = cols * rows
self.rect = self.spritesheet.get_rect()
w = self.cell_width = self.rect.width // self.cols
h = self.cell_height = self.rect.height // self.rows
self.cells = list([(i % cols * w, i // cols * h, w, h) for i in range(self.cell_count)])
def draw(self, surface, piece_name, coords):
piece_index = self.pieces[piece_name]
surface.blit(self.spritesheet, coords, self.cells[piece_index])
utils.py
import pygame
from pygame.locals import *
import queue
class Utils:
def get_mouse_event(self):
# get coordinates of the mouse
position = pygame.mouse.get_pos()
# return left click status and mouse coordinates
return position
def left_click_event(self):
# store mouse buttons
mouse_btn = pygame.mouse.get_pressed()
# create flag to check for left click event
left_click = False
if mouse_btn[0]: #and e.button == 1:
# change left click flag
left_click = True
return left_click
How To Run Chess Game In Python?
Here’s the step on How To Run Chess Game In Python.
Open Project Folder And Type This Following Command.
Open the project folder and type cmd on the directory and type the following command.
py main.py
Download Full Source Code
You can visit this site to download the other version of Chess Game for free.
Conclusion
We have completely built a chess game in python, also we learned with the help of example source codes.
I hope this python game project will help you a lot.