Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java Chess

A complete desktop chess application built in Java with a Swing based graphical interface. The project takes the player through the full lifecycle of a chess experience: account registration, authentication, game creation, real time gameplay against a computer opponent, and persistent progress tracking across sessions.

Overview

Chess World is a single player chess application where a human user competes against a computer controlled opponent. The application manages user accounts, tracks multiple simultaneous games per user, calculates scoring based on captured pieces and match outcomes, and persists all data between sessions using JSON files.

The interface is built entirely with Java Swing, using a combination of absolute positioning, GridBagLayout, and custom painted components to achieve a polished, modern look without relying on external UI frameworks.

Features

  • User registration and login with input validation
  • Persistent user accounts with cumulative point totals
  • Support for multiple simultaneous, resumable games per user
  • Full chess rule implementation, including check and checkmate detection
  • Draw detection through move repetition
  • Pawn promotion with piece selection dialog
  • Computer opponent with legal random move selection
  • Dynamic, resizable chess board with coordinate flipping for the black side perspective
  • Piece rendering through image assets with a Unicode symbol fallback
  • Victory and defeat screens with detailed point breakdowns
  • Continue Game menu listing all active matches with turn and score information
  • JSON based save and load system for accounts and games

Technical Architecture

The application is organized around a central JFrame (Main) that uses a CardLayout to switch between distinct screens without creating new windows. All shared application state, such as the logged in user, the map of registered accounts, and the map of active games, is centralized in a singleton GameEngine instance.

Each screen is implemented as an independent JPanel subclass responsible for its own layout and event handling, which keeps the navigation logic in Main decoupled from the presentation logic in each panel.

Chess logic is fully separated from the interface. The Board, Game, Player, and Piece hierarchy operate independently of Swing and could, in principle, be reused with a different front end.

Design Patterns

Singleton GameEngine guarantees a single, globally accessible instance responsible for user authentication, game management, and data persistence.

Factory PieceFactory creates concrete piece instances (King, Queen, Rook, Bishop, Knight, Pawn) from a type character, including reconstruction from serialized JSON data and pawn promotion. PieceSymbolFactory generates the corresponding Unicode chess symbols used as a rendering fallback.

Strategy Distinct coloring strategies are applied when displaying captured pieces, differentiating pieces captured by the player from pieces lost by the player.

Observer style updates The game screen listens for state changes such as a completed move, a captured piece, or a player turn switch, and refreshes only the relevant interface elements instead of repainting the entire panel.

CardLayout navigation Main relies on CardLayout to manage the application flow between the login, register, menu, continue game, active game, and result screens, treating each as an interchangeable card within a single container.

Project Structure

src/
  Main.java                Application entry point and screen navigation
  GameEngine.java           Singleton managing users, games, and persistence
  User.java                 User account model
  Player.java                In game player model (human or computer)
  Game.java                  Match orchestration and turn logic
  Board.java                 Board state and move validation
  Position.java               Board coordinate representation
  Move.java                    Record of an executed move
  ChessPair.java                 Generic sorted key value pair
  ChessPiece.java                  Interface implemented by all pieces
  Piece.java                        Abstract base class for chess pieces
  King.java, Queen.java, Rook.java, Bishop.java, Knight.java, Pawn.java
  PieceFactory.java                    Factory for piece creation
  PieceSymbolFactory.java                Factory for Unicode piece symbols
  JsonReaderUtil.java                      JSON serialization utilities
  InvalidMoveException.java                  Illegal move exception
  InvalidCommandException.java                 Invalid command exception

  LoginPanel.java, RegisterPanel.java          Authentication screens
  MenuPanel.java                                 Main menu screen
  ContinuePanel.java                              Active games list screen
  GameOptionsPanel.java                             Selected game options screen
  GamePanel.java                                     Live gameplay screen
  ChessGUIPanel.java                                   Visual chess board component
  VictoryPanel.java, DefeatPanel.java                    Match result screens

Core Classes

Main

The application window. Initializes the GameEngine, loads persisted data on startup, and exposes navigation methods such as showMenu(), showGame(Game), showVictoryPanel(...), and showDefeatPanel(...). Saves all data on window close.

GameEngine

The single source of truth for application state. Responsibilities include:

  • Authenticating and registering users
  • Creating new games and assigning a computer opponent with the opposite color
  • Tracking all active games in a map keyed by game id
  • Retrieving the list of active games for a given user
  • Reading and writing all persisted data through JsonReaderUtil

User

Represents a registered account: email, password, cumulative point total, and the list of games currently in progress.

Player

Represents one side of a match, human or computer. Tracks the pieces captured during the current game and the points accumulated from those captures. Delegates move execution to Board and updates its own state based on the result.

Game

Coordinates a single match from start to finish:

  • start() initializes the board and resets scores for a brand new match
  • resume() restores an in progress match from saved state
  • switchPlayer() alternates the active color after each move
  • checkForCheckMate() determines whether the player to move has any legal escape from check
  • checkForDrawByRepetition() detects a draw based on a repeating three fold move pattern
  • computerMove(Random) selects and executes a random legal move for the computer opponent

Board

Maintains the current arrangement of pieces using a position keyed map and enforces move legality:

  • initialize() sets up the standard starting position
  • movePiece(from, to) executes a move after validation, removing any captured piece
  • isValidMove(from, to) checks that a move is geometrically legal for the piece and does not leave the moving player's king in check, using a temporary board copy to simulate the result
  • isKingInCheck(color) scans all opposing pieces to determine whether the king is currently attacked
  • copyBoard() produces a deep copy used for safe move simulation

Piece hierarchy

An abstract Piece class implements the shared ChessPiece interface and is extended by King, Queen, Rook, Bishop, Knight, and Pawn. Each subclass implements getPossibleMoves(Board) according to its own movement rules, returning the set of raw candidate destinations before check safety filtering is applied by Board.

PieceFactory and PieceSymbolFactory

PieceFactory centralizes piece instantiation both for new games and for reconstruction from JSON, and also handles pawn promotion. PieceSymbolFactory maps a piece type and color to its Unicode glyph, used whenever image assets are unavailable.

Game Logic and Algorithms

Move validation follows a two stage process. First, the destination is checked against the piece's raw possible moves. Second, the move is simulated on a temporary board copy to confirm that executing it would not leave the moving player's own king in check. Only moves that pass both stages are considered legal.

Checkmate detection first confirms that the current player's king is in check, then iterates over every piece owned by that player and every one of its candidate destinations, checking each against full move validation. If no legal move removes the check, the position is checkmate.

Draw by repetition compares the hashes of the last six recorded moves. If moves one, three, and five match, and moves two, four, and six match, the game is declared a draw.

Computer move selection builds the complete list of legal moves available to the computer player, using the same validation logic applied to human moves, and selects one uniformly at random. If no legal move exists, the engine reports either checkmate or stalemate depending on whether the computer's king is currently in check.

Coordinate conversion in ChessGUIPanel translates between grid based interface coordinates and logical board positions, flipping the mapping when the human player controls the black pieces so that the board is always displayed from the current player's own perspective.

Scoring awards points based on the standard relative value of captured pieces (queen, rook, bishop, knight, pawn), with the running total displayed in both the live game screen and the final result screens, alongside any additional bonus applied at the end of the match.

Data Persistence

All user accounts and active games are serialized to JSON through JsonReaderUtil. On startup, Main loads the stored user map and reconstructs every active game, including board state, player data, and move history. On every meaningful state change, such as account creation, game creation, or window close, the current state is written back to disk so that progress is never lost between sessions.

User Interface Flow

Login / Register
      |
      v
    Menu -----------------------------+
      |                                |
      v                                v
  New Game                     Continue Game (active list)
      |                                |
      v                                v
                 Game Screen
                      |
          +-----------+-----------+
          v                       v
      Victory                 Defeat
          |                       |
          +-----------+-----------+
                      v
                    Menu

Each screen is added to the shared CardLayout container and swapped in without destroying application state held in GameEngine, allowing the user to navigate freely between the menu, active games, and settings without losing progress.

Exception Handling

  • InvalidMoveException is thrown by Board and Player whenever a requested move violates chess rules, targets an empty square incorrectly, or would leave the king in check. The exception message identifies the specific reason the move was rejected.
  • InvalidCommandException is reserved for invalid interface level commands outside the core move validation path.

Getting Started

  1. Clone the repository.
  2. Ensure the src/poze and src/pieces directories contain the required background, logo, and piece image assets referenced by the interface classes.
  3. Compile all classes with a standard Java compiler, for example:
    javac -d out src/*.java
    
  4. Run the application entry point:
    java -cp out Main
    
  5. On first launch, register a new account from the login screen to begin playing.

About

A complete Java Swing desktop chess client with custom-painted UI elements, AI opponent, score tracking, multi-game support, and JSON persistence.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages