0% found this document useful (0 votes)
20 views23 pages

Chess Hobby 2

The document details a project titled 'Chess Game' developed in Java as part of a Bachelor of Technology program in Computer Science and Engineering. It outlines the game's implementation, including features like move validation, turn management, and a graphical user interface, aimed at providing both educational and entertainment value. The project is designed for future enhancements, such as AI integration, and serves as a platform for understanding chess mechanics.

Uploaded by

238r1a6667
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views23 pages

Chess Hobby 2

The document details a project titled 'Chess Game' developed in Java as part of a Bachelor of Technology program in Computer Science and Engineering. It outlines the game's implementation, including features like move validation, turn management, and a graphical user interface, aimed at providing both educational and entertainment value. The project is designed for future enhancements, such as AI integration, and serves as a platform for understanding chess mechanics.

Uploaded by

238r1a6667
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

A HOBBY PROJECT

On
CHESS GAME
Submitted to CMREC (UGC Autonomous)
In Partial Fulfillment of the requirements for the Award of Degree of
BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE AND ENGINEERING
(Artificial Intelligence and Machine Learning)

Submitted By
A.Gowtham sai-238R1A6667
G.Shiva -238R1A6675
M.Pranay -238R1A6694
A.Revanth -238R1A6666
Under the guidance of
Mr.D.Sivaraj Kumar
Assistant Professor, Department of CSE(AI & ML)

Department of Computer Science & Engineering(AI & ML)


CMR ENGINEERING COLLEGE
(Accredited by NBA, Approved by AICTE, NEW DELHI, Affiliated to JNTU, Hyderabad)

Kandlakoya, Medchal Road, R.R. Dist. Hyderabad-501 401)


2023-2024
CERTIFICATE
This is to certify that the project entitled “CHESS GAME” is a word

carried out by
A.Gowtham Sai -238R1A6667
G.shiva -238R1A6675
M.Pranay -238R1A6694
A.Revanth -238R1A6666

in the part of innovative teaching methodology PBL Project of CHESS GAME of


JAVA Laboratory

Internal Guide Head of the Department


Mr..D.SIVARAJ KUMAR Dr. M . KUMARASWAMY
Assistant Professor Professor & HOD
Department of CSE(AI & ML), Department of CSE(AI & ML)
CMREC, Hyderabad CMREC, Hyderabad
DECLARATION

This is to certify that the work reported in the present project entitled " CHESS GAME " is a
record of word done by us in the Department of Computer Science and Engineering(AI & ML),
CMR Engineering College. I submit my project for further development by any interested
students who share similar interests to improve the project in the future.

A.Gowtham sai-238R1A6667
G.Shiva -238R1A6675
M.Pranay -238R1A6694
A.Revanth -238R1A6666
CREATE A CHESS GAME

Abstract
The Chess Game in Java is a computer-based implementation of the
classic board game chess. This project provides an interactive
platform where two players can compete against each other by
making legal moves on a chessboard, adhering to the rules and
strategies of the game. The game utilizes Java's object-oriented
programming principles, representing each chess piece as an object
with distinct properties and movement patterns. The board is
represented in a grid format, and each piece is placed in its initial
position at the start of the game.

The core of the program includes the game engine that handles move
validation, player turns, check/checkmate detection, and other chess
rules. It also features a graphical user interface (GUI) that provides an
intuitive visual representation of the game, allowing users to drag and
drop pieces, making the game more engaging. The system also
supports basic features like undoing moves, game restart, and the
display of a game status (e.g., check, checkmate, or stalemate).

The Chess Game in Java serves as both an educational tool and an


entertainment platform, offering an opportunity to understand the
game mechanics while also providing a fun and challenging
experience. The design and implementation focus on simplicity,
scalability, and maintainability, making it easy to enhance or extend
the game in the future (e.g., adding AI for single-player mode).
INTRODUCTION
1. Chess Overview:
1. Chess is a classic strategy board game with two players,
each controlling 16 pieces: pawns, rooks, knights, bishops,
a queen, and a king. The objective is to checkmate the
opponent's king.
2. Purpose of the Game:
1. The Chess Game in Java provides a digital version of
chess, allowing users to play the game on a computer. It
aims to simulate the traditional board game with all its
rules and features.
3. Technology Used:
1. The game is implemented in Java, an object-oriented
programming language that allows for clean, scalable, and
maintainable code.
4. Game Logic:
1. The core of the game includes features like move
validation, turn management, check/checkmate detection,
and other chess rules to ensure the game is played
accurately.
5. Graphical User Interface (GUI):
1. The game includes a GUI that visually represents the
chessboard and the pieces. Players can interact with the
game by dragging and dropping pieces, making it intuitive
and easy to play.
6. Features:
1. The game supports legal move detection, check and
checkmate status, player turn management, and game
restart options.
7. Educational and Entertainment Value:
1. This game serves as both an educational tool to understand
chess mechanics and a source of entertainment for players
looking for a challenging and engaging experience.
8. Future Enhancements:
1. The game is designed to be extensible, allowing for future
improvements such as AI integration for single-player
mode, additional features, and enhanced graphics
How the Chess Game in Java Works
The Chess Game in Java operates by simulating the game of chess
through a combination of object-oriented design, user input handling,
and graphical output. Here’s an overview of how the game works:

1. Initial Setup
 Board Representation:
o The chessboard is represented as an 8x8 grid, with each
square on the grid holding a piece or being empty.
o Each chess piece is modeled as an object with properties
and behaviors, such as color, type (king, queen, knight,
etc.), and legal movement patterns.
 Initial Piece Placement:
o At the start of the game, the pieces are arranged in their
standard starting positions on the board (e.g., rooks on the
corners, pawns on the second row, etc.).

2. Game Logic
 Move Validation:
o The game checks if a move is valid based on the piece type
and the rules of chess. For example, pawns can only move
forward but capture diagonally, while knights move in an
L-shape.
 Turn Management:
o Players alternate turns, with one player controlling the
white pieces and the other controlling the black pieces.
The game automatically checks for turn-based movement.
 Check and Checkmate Detection:
o After each move, the game checks if either king is in
"check" (under attack) or "checkmate" (unable to escape
check). If checkmate occurs, the game ends.
 Special Moves:
o The game also supports special moves like castling, en
passant, and pawn promotion, which are handled by
specific game logic.
3. Graphical User Interface (GUI)
 Visual Representation:
o The GUI provides a graphical representation of the
chessboard, displaying the chess pieces on the screen.
Each piece is represented by an image or icon.
 User Interaction:
o Players interact with the game by clicking or dragging
pieces. When a player selects a piece, the valid moves are
highlighted on the board, and the piece can be dragged to a
valid destination square.
 Move Execution:
o After a move is made, the chessboard updates to reflect the
new positions of the pieces. The game ensures that only
legal moves are executed.

4. Game End and Restart


 Check/Checkmate Notification:
o The game displays a message when a check or checkmate
situation occurs. The game announces the winner or
prompts the user to restart if the game is over.
 Game Restart:
o After a game ends, players can restart the game with a
fresh board and pieces in their initial positions.

5. Additional Features
 Undo Move:
o Some implementations may offer an undo feature to
reverse the last move, allowing players to correct mistakes.
 Game Status:
o The game displays real-time information about the current
player’s turn, whether it’s "White’s turn" or "Black’s turn,"
and whether the game is in check or checkmate.
Diagram of How the Chess Game Works:

Summary:
 The game initializes with pieces placed on the board.
 Players take turns making moves, with each move validated
based on chess rules.
 The GUI allows players to interact with the board visually
making moves by dragging and dropping pieces.
 The game continuously checks for special conditions like
 check and checkmate and notifies the players when the game
ends.
 The game can be restarted for a new match after it concludes.
board[start.getRow()][start.getColumn()].isValidMove(end,
board)) {

board[end.getRow()][end.getColumn()] =
board[start.getRow()][start.getColumn()];
board[end.getRow()][end.getColumn()].setPosition(end);
board[start.getRow()][start.getColumn()] = null;
}
}
}

CHESS GAME

import java.util.List;
import java.util.ArrayList;

public class ChessGame {


private ChessBoard board;
private boolean whiteTurn = true; // White starts the game

public ChessGame() {
this.board = new ChessBoard();
}

public ChessBoard getBoard() {


return this.board;
}

public void resetGame() {


this.board = new ChessBoard();
this.whiteTurn = true;
}

public PieceColor getCurrentPlayerColor() {


return whiteTurn ? PieceColor.WHITE : PieceColor.BLACK;
}
private Position selectedPosition;

public boolean isPieceSelected() {


return selectedPosition != null;
}

public boolean handleSquareSelection(int row, int col) {


if (selectedPosition == null) {
Piece selectedPiece = board.getPiece(row, col);
if (selectedPiece != null
&& selectedPiece.getColor() == (whiteTurn ?
PieceColor.WHITE : PieceColor.BLACK)) {
selectedPosition = new Position(row, col);
return false;
}
} else {
boolean moveMade = makeMove(selectedPosition, new
Position(row, col));
selectedPosition = null;
return moveMade;
}
return false;
}

public boolean makeMove(Position start, Position end) {


Piece movingPiece = board.getPiece(start.getRow(),
start.getColumn());
if (movingPiece == null || movingPiece.getColor() != (whiteTurn
? PieceColor.WHITE : PieceColor.BLACK)) {
return false;
}

if (movingPiece.isValidMove(end, board.getBoard())) {
board.movePiece(start, end);
whiteTurn = !whiteTurn;
return true;
}
return false;
}

public boolean isInCheck(PieceColor kingColor) {


Position kingPosition = findKingPosition(kingColor);
for (int row = 0; row < board.getBoard().length; row++) {
for (int col = 0; col < board.getBoard()[row].length; col++) {
Piece piece = board.getPiece(row, col);
if (piece != null && piece.getColor() != kingColor) {
if (piece.isValidMove(kingPosition, board.getBoard())) {
return true;
}
}
}
}
return false;
}

private Position findKingPosition(PieceColor color) {


for (int row = 0; row < board.getBoard().length; row++) {
for (int col = 0; col < board.getBoard()[row].length; col++) {
Piece piece = board.getPiece(row, col);
if (piece instanceof King && piece.getColor() == color) {
return new Position(row, col);
}
}
}
throw new RuntimeException("King not found, which should
never happen.");
}

public boolean isCheckmate(PieceColor kingColor) {


if (!isInCheck(kingColor)) {
return false;
}
Position kingPosition = findKingPosition(kingColor);
King king = (King) board.getPiece(kingPosition.getRow(),
kingPosition.getColumn());

for (int rowOffset = -1; rowOffset <= 1; rowOffset++) {


for (int colOffset = -1; colOffset <= 1; colOffset++) {
if (rowOffset == 0 && colOffset == 0) {
continue;
}
Position newPosition = new Position(kingPosition.getRow()
+ rowOffset,
kingPosition.getColumn() + colOffset);

if (isPositionOnBoard(newPosition) &&
king.isValidMove(newPosition, board.getBoard())
&& !wouldBeInCheckAfterMove(kingColor,
kingPosition, newPosition)) {
return false;
}
}
}
return true;
}

private boolean isPositionOnBoard(Position position) {


return position.getRow() >= 0 && position.getRow() <
board.getBoard().length &&
position.getColumn() >= 0 && position.getColumn() <
board.getBoard()[0].length;
}

private boolean wouldBeInCheckAfterMove(PieceColor kingColor,


Position from, Position to) {
Piece temp = board.getPiece(to.getRow(), to.getColumn());
board.setPiece(to.getRow(), to.getColumn(),
board.getPiece(from.getRow(), from.getColumn()));
board.setPiece(from.getRow(), from.getColumn(), null);
boolean inCheck = isInCheck(kingColor);

board.setPiece(from.getRow(), from.getColumn(),
board.getPiece(to.getRow(), to.getColumn()));
board.setPiece(to.getRow(), to.getColumn(), temp);

return inCheck;
}

public List<Position> getLegalMovesForPieceAt(Position position)


{
Piece selectedPiece = board.getPiece(position.getRow(),
position.getColumn());
if (selectedPiece == null)
return new ArrayList<>();

List<Position> legalMoves = new ArrayList<>();


switch (selectedPiece.getClass().getSimpleName()) {
case "Pawn":
addPawnMoves(position, selectedPiece.getColor(),
legalMoves);
break;
case "Rook":
addLineMoves(position, new int[][] { { 1, 0 }, { -1, 0 }, { 0,
1 }, { 0, -1 } }, legalMoves);
break;
case "Knight":
addSingleMoves(position, new int[][] { { 2, 1 }, { 2, -1 }, { -
2, 1 }, { -2, -1 }, { 1, 2 }, { -1, 2 },
{ 1, -2 }, { -1, -2 } }, legalMoves);
break;
case "Bishop":
addLineMoves(position, new int[][] { { 1, 1 }, { -1, -1 }, { 1,
-1 }, { -1, 1 } }, legalMoves);
break;
case "Queen":
addLineMoves(position, new int[][] { { 1, 0 }, { -1, 0 }, { 0,
1 }, { 0, -1 }, { 1, 1 }, { -1, -1 },
{ 1, -1 }, { -1, 1 } }, legalMoves);
break;
case "King":
addSingleMoves(position, new int[][] { { 1, 0 }, { -1, 0 }, {
0, 1 }, { 0, -1 }, { 1, 1 }, { -1, -1 },
{ 1, -1 }, { -1, 1 } }, legalMoves);
break;
}
return legalMoves;
}

private void addLineMoves(Position position, int[][] directions,


List<Position> legalMoves) {
for (int[] d : directions) {
Position newPos = new Position(position.getRow() + d[0],
position.getColumn() + d[1]);
while (isPositionOnBoard(newPos)) {
if (board.getPiece(newPos.getRow(), newPos.getColumn())
== null) {
legalMoves.add(new Position(newPos.getRow(),
newPos.getColumn()));
newPos = new Position(newPos.getRow() + d[0],
newPos.getColumn() + d[1]);
} else {
if (board.getPiece(newPos.getRow(),
newPos.getColumn()).getColor() != board
.getPiece(position.getRow(),
position.getColumn()).getColor()) {
legalMoves.add(newPos);
}
break;
}
}
}
}
private void addSingleMoves(Position position, int[][] moves,
List<Position> legalMoves) {
for (int[] move : moves) {
Position newPos = new Position(position.getRow() + move[0],
position.getColumn() + move[1]);
if (isPositionOnBoard(newPos) &&
(board.getPiece(newPos.getRow(), newPos.getColumn()) == null ||
board.getPiece(newPos.getRow(),
newPos.getColumn()).getColor() != board
.getPiece(position.getRow(),
position.getColumn()).getColor())) {
legalMoves.add(newPos);
}
}
}

private void addPawnMoves(Position position, PieceColor color,


List<Position> legalMoves) {
int direction = color == PieceColor.WHITE ? -1 : 1;
Position newPos = new Position(position.getRow() + direction,
position.getColumn());
if (isPositionOnBoard(newPos) &&
board.getPiece(newPos.getRow(), newPos.getColumn()) == null) {
legalMoves.add(newPos);
}

if ((color == PieceColor.WHITE && position.getRow() == 6)


|| (color == PieceColor.BLACK && position.getRow() ==
1)) {
newPos = new Position(position.getRow() + 2 * direction,
position.getColumn());
Position intermediatePos = new Position(position.getRow() +
direction, position.getColumn());
if (isPositionOnBoard(newPos) &&
board.getPiece(newPos.getRow(), newPos.getColumn()) == null
&& board.getPiece(intermediatePos.getRow(),
intermediatePos.getColumn()) == null) {
legalMoves.add(newPos);
}
}

int[] captureCols = { position.getColumn() - 1,


position.getColumn() + 1 };
for (int col : captureCols) {
newPos = new Position(position.getRow() + direction, col);
if (isPositionOnBoard(newPos) &&
board.getPiece(newPos.getRow(), newPos.getColumn()) != null &&
board.getPiece(newPos.getRow(),
newPos.getColumn()).getColor() != color) {
legalMoves.add(newPos);
}
}
}
}

CHESSGAME GUI

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

public class ChessGameGUI extends JFrame {


private final ChessSquareComponent[][] squares = new
ChessSquareComponent[8][8];
private final ChessGame game = new ChessGame();
private final Map<Class<? extends Piece>, String>
pieceUnicodeMap = new HashMap<>() {
{
put(Pawn.class, "\u265F");
put(Rook.class, "\u265C");
put(Knight.class, "\u265E");
put(Bishop.class, "\u265D");
put(Queen.class, "\u265B");
put(King.class, "\u265A");
}
};

public ChessGameGUI() {
setTitle("Chess Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(8, 8));
initializeBoard();
addGameResetOption();
pack();
setVisible(true);
}

private void initializeBoard() {


for (int row = 0; row < squares.length; row++) {
for (int col = 0; col < squares[row].length; col++) {
final int finalRow = row;
final int finalCol = col;
ChessSquareComponent square = new
ChessSquareComponent(row, col);
square.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
handleSquareClick(finalRow, finalCol);
}
});
add(square);
squares[row][col] = square;
}
}
refreshBoard();
}

private void refreshBoard() {


ChessBoard board = game.getBoard();
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
Piece piece = board.getPiece(row, col);
if (piece != null) {
// If using Unicode symbols:
String symbol = pieceUnicodeMap.get(piece.getClass());
Color color = (piece.getColor() == PieceColor.WHITE) ?
Color.WHITE : Color.BLACK;
squares[row][col].setPieceSymbol(symbol, color);
} else {
squares[row][col].clearPieceSymbol();
}
}
}
}

private void handleSquareClick(int row, int col) {


boolean moveResult = game.handleSquareSelection(row, col);
clearHighlights();
if (moveResult) {
refreshBoard();
checkGameState();
checkGameOver();
} else if (game.isPieceSelected()) {
highlightLegalMoves(new Position(row, col));
}
refreshBoard();
}

private void checkGameState() {


PieceColor currentPlayer = game.getCurrentPlayerColor();
boolean inCheck = game.isInCheck(currentPlayer);

if (inCheck) {
JOptionPane.showMessageDialog(this, currentPlayer + " is in
check!");
}
}

private void highlightLegalMoves(Position position) {


List<Position> legalMoves =
game.getLegalMovesForPieceAt(position);
for (Position move : legalMoves) {

squares[move.getRow()][move.getColumn()].setBackground(Color.G
REEN);
}
}

private void clearHighlights() {


for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
squares[row][col].setBackground((row + col) % 2 == 0 ?
Color.LIGHT_GRAY : new Color(205, 133, 63));
}
}
}

private void addGameResetOption() {


JMenuBar menuBar = new JMenuBar();
JMenu gameMenu = new JMenu("Game");
JMenuItem resetItem = new JMenuItem("Reset");
resetItem.addActionListener(e -> resetGame());
gameMenu.add(resetItem);
menuBar.add(gameMenu);
setJMenuBar(menuBar);
}
private void resetGame() {
game.resetGame();
refreshBoard();
}

private void checkGameOver() {


if (game.isCheckmate(game.getCurrentPlayerColor())) {
int response = JOptionPane.showConfirmDialog(this,
"Checkmate! Would you like to play again?", "Game Over",
JOptionPane.YES_NO_OPTION);
if (response == JOptionPane.YES_OPTION) {
resetGame();
} else {
System.exit(0);
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(ChessGameGUI::new);
}
}

CHESS SQUARE COMPONENT:


import javax.swing.*;
import java.awt.*;

public class ChessSquareComponent extends JButton {


private int row;
private int col;

public ChessSquareComponent(int row, int col) {


this.row = row;
this.col = col;
initButton();
}

private void initButton() {


setPreferredSize(new Dimension(64, 64));

if ((row + col) % 2 == 0) {
setBackground(Color.LIGHT_GRAY);
} else {
setBackground(new Color(205, 133, 63));
}

setHorizontalAlignment(SwingConstants.CENTER);
setVerticalAlignment(SwingConstants.CENTER);
setFont(new Font("Serif", Font.BOLD, 36));
}

public void setPieceSymbol(String symbol, Color color) {


this.setText(symbol);
this.setForeground(color);
}

public void clearPieceSymbol() {


this.setText("");
}
}

POSITIONS:
public class Position {
private int row;
private int column;

public Position(int row, int column) {


this.row = row;
this.column = column;
}
Wrapping Up:

Building a Java chess game application is a great way to enhance your


Java development skills and delve into creating interactive Java
applications.

By creating this interactive Java chess game, you've navigated


through various challenges, from designing an intuitive interface to
implementing complex game logic and interactive gameplay.

In this tutorial, you’ve learned how to:

Utilize Java Swing to construct a visually appealing and functional


chess game GUI.
Craft Java code to establish the chess game logic, including piece
movement, capturing, and special moves like castling and en passant.
Dynamically update the Swing components to reflect the current state
of the game, providing real-time feedback to player actions.
Handle user interactions through event listeners for piece selection,
movement, and implementing game rules to ensure legal moves.
Incorporate advanced game features such as check and checkmate
detection, turn management, and highlighting legal moves for selected
pieces.
CONCLUSION
The Chess Game in Java provides an interactive and realistic digital
experience of chess, with a user-friendly graphical interface and
accurate game logic. It handles move validation, turn-based play, and
check/checkmate detection, ensuring a smooth and strategic gameplay
experience. The game is modular and scalable, allowing for future
enhancements like AI for single-player mode. Overall, it successfully
combines programming techniques with the classic game of chess,
making it both a valuable learning tool and an enjoyable game for
players.

You might also like