The Chess Game Program In Python is one of the oldest and most popular board games in the world. Whether you want to study chess to play casual games with your friends or compete, you’ll find everything you need to know about how to create this game in Python and how to play it.
In addition, this Chess Game Using Python is useful for learning new skills and practicing Python game development.
This project is quite useful, and the concept and logic of the project are simple to grasp.
How To Play Chess Game Program In Python?
Chess is a game in which two players compete on opposite sides of a 64-square board with alternating colors.
Each player starts with 16 pieces, including a king, queen, two rooks, two bishops, two knights, and eight pawns. The game’s objective is to checkmate the opposing king.
Benefits Of Playing Chess Game
Chess improves memory – Expert chess players have excellent recall skills, which may come as no surprise. After all, the game necessitates memorizing a large number of different moves and their possible outcomes.
It’s also worth noting that experienced chess players have better performance when it comes to a certain type of memory: auditory memory.
This is the ability to recall information obtained through hearing.
Chess improves planning abilities – Long periods of silent contemplation are common in chess games, during which players consider each move.
Players spend a lot of effort anticipating their opponents’ reactions and attempting to foresee every possible scenario.
One of the cognitive health benefits of chess is the practice of mind-careful thought and planning.
Project Details and Technology
Project Name: | Chess Game Program In Python |
Abstract: | This Chess Game Program is a fantastic game for users who enjoy playing chess in their spare time, as well as students that require this type of project. |
Language/s Used: | Python (GUI Based) |
Python version (Recommended): | 3.8 or 3.9 |
Type: | Desktop Application |
Developer: | Glenn Magada Azuelo |
Updates: | 0 |
About the Project
The Chess Game In Python With Source Code is a simple desktop application made using the Python programming language.
We may also create highly fascinating games with the Python programming language.
This Chess Game With Python includes a tutorial and a code development guide. This is a simple and basic-level little project for learning purposes.
Chess game is open source, so you can download the zip file and change it to fit your needs.
You can also customize this project to meet your needs and create a fantastic advanced-level project.
How To Build A Chess Game In Python
The code given below is the full source code on How To Build A Chess Game.
The given code below is a Python file for chess.py
import chess_engine
import pygame as py
import ai_engine
from enums import Player
"""Variables"""
WIDTH = HEIGHT = 512 # width and height of the chess board
DIMENSION = 8 # the dimensions of the chess board
SQ_SIZE = HEIGHT // DIMENSION # the size of each of the squares in the board
MAX_FPS = 15 # FPS for animations
IMAGES = {} # images for the chess pieces
colors = [py.Color("white"), py.Color("gray")]
# TODO: AI black has been worked on. Mirror progress for other two modes
def load_images():
'''
Load images for the chess pieces
'''
for p in Player.PIECES:
IMAGES[p] = py.transform.scale(py.image.load("images/" + p + ".png"), (SQ_SIZE, SQ_SIZE))
def draw_game_state(screen, game_state, valid_moves, square_selected):
''' Draw the complete chess board with pieces
Keyword arguments:
:param screen -- the pygame screen
:param game_state -- the state of the current chess game
'''
draw_squares(screen)
highlight_square(screen, game_state, valid_moves, square_selected)
draw_pieces(screen, game_state)
def draw_squares(screen):
''' Draw the chess board with the alternating two colors
:param screen: -- the pygame screen
'''
for r in range(DIMENSION):
for c in range(DIMENSION):
color = colors[(r + c) % 2]
py.draw.rect(screen, color, py.Rect(c * SQ_SIZE, r * SQ_SIZE, SQ_SIZE, SQ_SIZE))
def draw_pieces(screen, game_state):
''' Draw the chess pieces onto the board
:param screen: -- the pygame screen
:param game_state: -- the current state of the chess game
'''
for r in range(DIMENSION):
for c in range(DIMENSION):
piece = game_state.get_piece(r, c)
if piece is not None and piece != Player.EMPTY:
screen.blit(IMAGES[piece.get_player() + "_" + piece.get_name()],
py.Rect(c * SQ_SIZE, r * SQ_SIZE, SQ_SIZE, SQ_SIZE))
def highlight_square(screen, game_state, valid_moves, square_selected):
if square_selected != () and game_state.is_valid_piece(square_selected[0], square_selected[1]):
row = square_selected[0]
col = square_selected[1]
if (game_state.whose_turn() and game_state.get_piece(row, col).is_player(Player.PLAYER_1)) or \
(not game_state.whose_turn() and game_state.get_piece(row, col).is_player(Player.PLAYER_2)):
# hightlight selected square
s = py.Surface((SQ_SIZE, SQ_SIZE))
s.set_alpha(100)
s.fill(py.Color("blue"))
screen.blit(s, (col * SQ_SIZE, row * SQ_SIZE))
# highlight move squares
s.fill(py.Color("green"))
for move in valid_moves:
screen.blit(s, (move[1] * SQ_SIZE, move[0] * SQ_SIZE))
def main():
# Check for the number of players and the color of the AI
human_player = ""
while True:
try:
number_of_players = input("How many players (1 or 2)?\n")
if int(number_of_players) == 1:
number_of_players = 1
while True:
human_player = input("What color do you want to play (w or b)?\n")
if human_player is "w" or human_player is "b":
break
else:
print("Enter w or b.\n")
break
elif int(number_of_players) == 2:
number_of_players = 2
break
else:
print("Enter 1 or 2.\n")
except ValueError:
print("Enter 1 or 2.")
py.init()
screen = py.display.set_mode((WIDTH, HEIGHT))
clock = py.time.Clock()
game_state = chess_engine.game_state()
load_images()
running = True
square_selected = () # keeps track of the last selected square
player_clicks = [] # keeps track of player clicks (two tuples)
valid_moves = []
game_over = False
ai = ai_engine.chess_ai()
game_state = chess_engine.game_state()
if human_player is 'b':
ai_move = ai.minimax_black(game_state, 3, -100000, 100000, True, Player.PLAYER_1)
game_state.move_piece(ai_move[0], ai_move[1], True)
while running:
for e in py.event.get():
if e.type == py.QUIT:
running = False
elif e.type == py.MOUSEBUTTONDOWN:
if not game_over:
location = py.mouse.get_pos()
col = location[0] // SQ_SIZE
row = location[1] // SQ_SIZE
if square_selected == (row, col):
square_selected = ()
player_clicks = []
else:
square_selected = (row, col)
player_clicks.append(square_selected)
if len(player_clicks) == 2:
# this if is useless right now
if (player_clicks[1][0], player_clicks[1][1]) not in valid_moves:
square_selected = ()
player_clicks = []
valid_moves = []
else:
game_state.move_piece((player_clicks[0][0], player_clicks[0][1]),
(player_clicks[1][0], player_clicks[1][1]), False)
square_selected = ()
player_clicks = []
valid_moves = []
if human_player is 'w':
ai_move = ai.minimax_white(game_state, 3, -100000, 100000, True, Player.PLAYER_2)
game_state.move_piece(ai_move[0], ai_move[1], True)
elif human_player is 'b':
ai_move = ai.minimax_black(game_state, 3, -100000, 100000, True, Player.PLAYER_1)
game_state.move_piece(ai_move[0], ai_move[1], True)
else:
valid_moves = game_state.get_valid_moves((row, col))
if valid_moves is None:
valid_moves = []
elif e.type == py.KEYDOWN:
if e.key == py.K_r:
game_over = False
game_state = chess_engine.game_state()
valid_moves = []
square_selected = ()
player_clicks = []
valid_moves = []
elif e.key == py.K_u:
game_state.undo_move()
print(len(game_state.move_log))
draw_game_state(screen, game_state, valid_moves, square_selected)
endgame = game_state.checkmate_stalemate_checker()
if endgame == 0:
game_over = True
draw_text(screen, "Black wins.")
elif endgame == 1:
game_over = True
draw_text(screen, "White wins.")
elif endgame == 2:
game_over = True
draw_text(screen, "Stalemate.")
clock.tick(MAX_FPS)
py.display.flip()
def draw_text(screen, text):
font = py.font.SysFont("Helvitca", 32, True, False)
text_object = font.render(text, False, py.Color("Black"))
text_location = py.Rect(0, 0, WIDTH, HEIGHT).move(WIDTH / 2 - text_object.get_width() / 2,
HEIGHT / 2 - text_object.get_height() / 2)
screen.blit(text_object, text_location)
if __name__ == "__main__":
main()
To learn more on How To Build A Chess Game In Python, just download the source code below.
By the way, if you are new to Python programming and don’t have any idea what Python IDE to use, I have here a list of the Best Python IDE for Windows, Linux, and Mac OS for you.
Additionally, I also have here How to Download and Install the Latest Version of Python on Windows.
To start executing a Chess Game, make sure that you have installed Python on your computer.
Steps On How To Run The Project
Time needed: 5 minutes
These are the steps on how to run Chess Game In Python with Source Code
- Step 1: Download Source Code
First, find the downloadable source code below and click to start downloading the source code file.
- Step 2: Extract File
Next, after finished to download the file, go to the file location right-click the file and click extract.
- Step 3 : Open PyCharm
Next, open pycharm IDE and open the project you’ve downloaded.
- Step 4: Run Project
Next, go to the Pycharm and click the run button to start executing the project.
Download the Source Code below!
Summary
This Article is a way to enhance and develop our skills and logic ideas which is important in practicing the Python programming language which is the most well-known and most usable programming language in many companies.
Inquiries
If you have any questions or suggestions about Chess Game In Python With Source Code, please feel free to leave a comment below.