Skip to content

Commit ad1ac9c

Browse files
authored
Merge pull request #12 from mgierschdev/copilot/update-readme-for-developers
Add comprehensive architecture documentation and class-level headers
2 parents bfb446d + 40d4d00 commit ad1ac9c

5 files changed

Lines changed: 419 additions & 11 deletions

File tree

README.md

Lines changed: 356 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
1+
# ChessEngine
2+
3+
## What this repository is
4+
5+
A web-based chess application with a custom chess engine backend and Next.js frontend. The backend is a Spring Boot REST API (Java 17) that implements chess game logic including move validation, check/checkmate detection, en passant, and pawn promotion. The frontend is a React-based TypeScript UI using Next.js 13 that communicates with the backend via HTTP. This is **not** a computer opponent—it enforces rules for two human players on the same machine. It is **not** a distributed multiplayer service.
6+
7+
## Why it exists
8+
9+
This project was created to demonstrate a full-stack chess implementation with RESTful communication between a Java backend and a modern TypeScript frontend. Intended users are developers learning chess engine logic, full-stack development patterns, or seeking a reference implementation of chess rules validation.
10+
11+
## Quickstart
12+
13+
**Prerequisites:**
14+
- Java 17 or higher
15+
- Node.js 18+ and npm (for frontend)
16+
- Gradle wrapper is included
17+
18+
**Run locally:**
19+
20+
1. **Start the backend:**
21+
```bash
22+
cd backend
23+
./gradlew bootRun
24+
```
25+
Backend runs on `http://localhost:8080`
26+
27+
2. **Install frontend dependencies (first time only):**
28+
```bash
29+
cd frontend
30+
npm install
31+
```
32+
33+
3. **Start the frontend:**
34+
```bash
35+
cd frontend
36+
npm run dev
37+
```
38+
Frontend runs on `http://localhost:3000`
39+
40+
4. Open `http://localhost:3000` in your browser to play chess.
41+
42+
**Run tests:**
43+
44+
Backend:
45+
```bash
46+
cd backend
47+
./gradlew test
48+
```
49+
50+
Frontend:
51+
```bash
52+
cd frontend
53+
npm install # if not already done
54+
npm test
55+
```
56+
57+
**Common troubleshooting:**
58+
- If backend fails to start, ensure Java 17+ is installed: `java -version`
59+
- If frontend build fails, delete `node_modules` and `package-lock.json`, then run `npm install` again
60+
- Backend must be running before frontend can fetch game state
61+
- CORS is configured for `http://localhost:3000` only
62+
63+
## Architecture at a glance
64+
65+
```mermaid
66+
graph TB
67+
subgraph Frontend["Frontend (Next.js, TypeScript)"]
68+
UI["React Components<br/>(Chessboard, RightSidePanel)"]
69+
Service["ChessService<br/>(API Client)"]
70+
Models["TypeScript Models"]
71+
end
72+
73+
subgraph Backend["Backend (Spring Boot, Java 17)"]
74+
Controller["ChessController<br/>(REST Endpoints)"]
75+
Game["ChessGame<br/>(Game State Manager)"]
76+
Board["Chessboard<br/>(Move Logic & Validation)"]
77+
DomainModels["Domain Models<br/>(ChessPiece, Position, etc.)"]
78+
end
79+
80+
UI -->|User clicks| Service
81+
Service -->|HTTP GET/POST| Controller
82+
Controller --> Game
83+
Game --> Board
84+
Board --> DomainModels
85+
Controller -->|JSON Response| Service
86+
Service --> Models
87+
Models -->|Props| UI
88+
```
89+
90+
**Data flow:**
91+
92+
1. User interacts with the chessboard UI in the browser.
93+
2. Frontend `ChessService` sends HTTP requests (GET `/chessGame`, POST `/move`, POST `/getValidMoves`) to the Spring Boot backend on localhost:8080.
94+
3. `ChessController` delegates to `ChessGame`, which manages turn state, captured pieces, and game state (check/checkmate).
95+
4. `ChessGame` uses `Chessboard` to validate moves and detect check/checkmate.
96+
5. `Chessboard` applies chess rules and returns results.
97+
6. Backend responds with JSON containing the updated board, turn, and game state.
98+
7. Frontend updates React state and re-renders the UI.
99+
100+
## Core components
101+
102+
**Backend (`/backend/src/main/java/com/backend`):**
103+
104+
- **`ApplicationStart.java`**: Spring Boot main entry point. Starts the REST API server. Also includes a console-based game runner (unused by frontend).
105+
- **`controllers/ChessController.java`**: REST controller exposing endpoints `/startGame`, `/endGame`, `/chessGame`, `/move`, `/getValidMoves`. Manages in-memory game instance (singleton per server run).
106+
- **`domain/ChessGame.java`**: Core game state manager. Tracks turn, captured pieces, game state (Free, Check, Checkmate). Delegates move logic to `Chessboard`.
107+
- **`domain/Chessboard.java`**: Implements chess board representation (8x8 matrix), move validation, check/checkmate detection, en passant, castling, and pawn promotion.
108+
- **`models/`**: Domain models (`ChessPiece`, `Position`, `Color`, `ChessPieceType`, `GameState`).
109+
- **`models/requests/`**: DTOs for HTTP request/response (`ChessGameResponse`, `PositionResponse`, `ChessboardMoveRequest`, etc.).
110+
- **`util/`**: Utility classes (`Util.java` for notation conversion, `Log.java` for static message strings).
111+
112+
**Frontend (`/frontend/src/app`):**
113+
114+
- **`page.tsx`**: Home page (server component). Fetches initial game state and renders `Chessboard` and `RightSidePanel`.
115+
- **`_client_components/Chessboard.tsx`**: Client component rendering the 8x8 board. Handles user clicks, valid move highlighting, and pawn promotion modal.
116+
- **`_client_components/ChessPieceCell.tsx`**: Individual cell with piece rendering.
117+
- **`_client_components/RightSidePanel.tsx`**: Displays turn, game state, and captured pieces.
118+
- **`_client_components/PromotionModal.tsx`**: Modal for pawn promotion piece selection.
119+
- **`_services/ChessService.tsx`**: HTTP client for backend API calls.
120+
- **`_models/`**: TypeScript interfaces mirroring backend models.
121+
122+
**Static assets (`/static`):**
123+
- **`Chessboard.afdesign`**: Design file for the chessboard (Affinity Designer format). Not used at runtime.
124+
125+
**SVG assets (`/frontend/public`):**
126+
- Chess piece SVG images (e.g., `WKing.svg`, `BPawn.svg`, etc.).
127+
128+
## Interfaces
129+
130+
**REST API (Backend):**
131+
132+
- `GET /startGame`: Initializes a new game. Returns `ChessGameResponse` with initial board state.
133+
- `GET /endGame`: Ends the current game and clears state. Returns confirmation message.
134+
- `GET /chessGame`: Returns current game state (board, turn, captured pieces, game state).
135+
- `POST /move`: Accepts `ChessboardMoveRequest` (source, target, optional promotionType). Returns `PositionResponse` (moved piece or error).
136+
- `POST /getValidMoves`: Accepts `Position`. Returns array of valid move positions for the piece at that position.
137+
138+
Example request (move):
139+
```json
140+
POST /move
141+
{
142+
"source": {"row": 2, "col": 5},
143+
"target": {"row": 4, "col": 5},
144+
"promotionType": "Queen"
145+
}
146+
```
147+
148+
**Frontend UI:**
149+
150+
- `/` (home): Main chessboard and game panel.
151+
- `/about`: About page (see `/frontend/src/app/about/page.tsx`).
152+
153+
**No CLI or file I/O**—all interaction is via browser and HTTP.
154+
155+
## Configuration
156+
157+
**Backend:**
158+
159+
- **`application.properties`**: Empty (`/backend/src/main/resources/application.properties`). Spring Boot uses defaults (port 8080, no database).
160+
- **No environment variables required**. All configuration is hardcoded or uses Spring Boot defaults.
161+
- **CORS origins**: Configured in `ChessController.java` as `@CrossOrigin(origins = {"http://localhost:3000/", "http://localhost:3000"})` (line 16 of `/backend/src/main/java/com/backend/controllers/ChessController.java`).
162+
163+
**Frontend:**
164+
165+
- **Backend API URL**: Hardcoded in `/frontend/src/app/_services/ChessService.tsx` as `http://localhost:8080/` (line 8).
166+
- **No environment variables used**. Configuration is in `next.config.js` (default Next.js config), `tsconfig.json`, `.eslintrc.json`.
167+
168+
**Secrets:**
169+
170+
No secrets, tokens, or credentials are required or stored. All communication is localhost HTTP (no TLS, no auth).
171+
172+
## Dependencies and external services
173+
174+
**Backend dependencies** (`/backend/build.gradle.kts`):
175+
176+
- `org.springframework.boot:spring-boot-starter-web` (Spring Boot 3.1.0) — REST API framework
177+
- `org.testng:testng:7.1.0` — Testing framework (though JUnit is also used)
178+
- `org.springframework.boot:spring-boot-starter-test` — JUnit 5 and Spring test utilities
179+
180+
**Frontend dependencies** (`/frontend/package.json`):
181+
182+
- `next` (13.4.4) — React framework
183+
- `react` (18.2.0), `react-dom` (18.2.0) — UI library
184+
- `typescript` (5.1.3) — Type safety
185+
- `eslint`, `eslint-config-next` — Linting
186+
- `jest`, `@testing-library/react`, `@testing-library/jest-dom` — Testing
187+
188+
**External services:**
189+
190+
None. The application runs entirely on localhost with no external API calls, databases, or cloud services.
191+
192+
**Build tools:**
193+
194+
- Gradle 7.6.1 (via wrapper) for backend (`/backend/gradle/wrapper/gradle-wrapper.properties`)
195+
- npm for frontend
196+
197+
## Quality and safety
198+
199+
**Tests:**
200+
201+
- **Backend**: 3 test files in `/backend/src/test/java`:
202+
- `BackendApplicationTests.java` — Spring context load test
203+
- `GameStateTest.java` — Tests check and checkmate scenarios
204+
- `ChessBoardTest.java` — (contents unknown, not inspected)
205+
- Run with: `cd backend && ./gradlew test`
206+
- Last run: ✅ Successful (4 actionable tasks executed)
207+
208+
- **Frontend**: 1 test file in `/frontend/src/app/_client_components`:
209+
- `RightSidePanel.test.tsx` — Tests checkmate rendering
210+
- Run with: `cd frontend && npm test` (requires `npm install` first)
211+
- Note: Tests are configured in `jest.config.js`
212+
213+
**CI:**
214+
215+
No GitHub Actions workflows, Travis CI, or CircleCI configurations found. CI is **not configured**.
216+
217+
**Linting and formatting:**
218+
219+
- **Backend**: No linter configured. Code style is not enforced.
220+
- **Frontend**: ESLint configured (`eslint-config-next`). Run with: `npm run lint` or `npm run lint-fix` (see `/frontend/package.json` scripts).
221+
222+
**Static analysis and security:**
223+
224+
- **No static analysis tools** (e.g., SonarQube, SpotBugs) configured.
225+
- **No dependency scanning** (e.g., Dependabot, Snyk) configured.
226+
- **No security scanning** (e.g., OWASP Dependency-Check) configured.
227+
228+
**Build verification:**
229+
230+
Backend builds successfully with `./gradlew build`. Frontend requires `npm install` before build/test.
231+
232+
## Sensitive information review
233+
234+
**Status:** Clean
235+
236+
**Reviewed areas:**
237+
238+
- `/backend/src/main/java` (all Java source files)
239+
- `/backend/src/main/resources/application.properties`
240+
- `/backend/build.gradle.kts`
241+
- `/frontend/src` (all TypeScript files)
242+
- `/frontend/package.json`, `/frontend/next.config.js`, `/frontend/jest.config.js`
243+
- `.gitignore` files in both backend and frontend
244+
- No `.env`, `.env.local`, or environment config files exist in the repository
245+
246+
**Findings:**
247+
248+
- **Hardcoded localhost URLs**: `http://localhost:8080` in `/frontend/src/app/_services/ChessService.tsx` (line 8) and `http://localhost:3000` in `/backend/src/main/java/com/backend/controllers/ChessController.java` (line 16).
249+
- These are local development URLs, not secrets. Safe for public repositories.
250+
- **No real secrets found**: No API keys, passwords, tokens, private keys, or credentials detected.
251+
252+
**Actions taken:**
253+
254+
None required. Repository is clean.
255+
256+
**Notes:**
257+
258+
- `*.pem` files are excluded by `/frontend/.gitignore` (line 20), which is good practice.
259+
- No environment variable injection mechanisms found.
260+
- No terraform, helm, docker-compose, or cloud configuration files found.
261+
- Binary/design files (e.g., `/static/Chessboard.afdesign`) were not inspected for embedded secrets.
262+
263+
## What's missing
264+
265+
### Documentation
266+
- **P1 / M**: API endpoint documentation (OpenAPI/Swagger spec). Next action: Add Springdoc OpenAPI dependency and annotate endpoints.
267+
- **P2 / S**: Architecture decision records (ADRs) for key design choices. Next action: Document why singleton game instance vs. database.
268+
269+
### Tests
270+
- **P0 / M**: No integration tests for the full frontend-backend flow. Next action: Add a test that starts both services and verifies a complete game flow.
271+
- **P1 / M**: Low backend test coverage (only 3 test files for 16 source files). Next action: Add tests for `Chessboard` move validation edge cases.
272+
- **P1 / S**: No frontend component tests beyond `RightSidePanel.test.tsx`. Next action: Add tests for `Chessboard.tsx` click handlers.
273+
274+
### Security
275+
- **P1 / M**: No HTTPS/TLS for production deployment. Next action: Document production deployment with reverse proxy (e.g., nginx) for TLS termination.
276+
- **P1 / S**: No input validation on backend (e.g., null checks are minimal). Next action: Add bean validation annotations to request DTOs.
277+
- **P2 / M**: No dependency vulnerability scanning. Next action: Enable Dependabot or integrate OWASP Dependency-Check.
278+
279+
### Reliability
280+
- **P0 / L**: Game state is in-memory (lost on server restart). No persistence. Next action: Add database (e.g., H2 or PostgreSQL) and game state serialization.
281+
- **P1 / M**: No error handling for network failures in frontend. Next action: Add retry logic and user-friendly error messages in `ChessService`.
282+
- **P2 / S**: No logging framework (only static log strings). Next action: Replace `Log` utility with SLF4J and configure log levels.
283+
284+
### Operations
285+
- **P0 / M**: No production deployment configuration (Docker, cloud deployment). Next action: Add `Dockerfile` for backend and frontend, and `docker-compose.yml` for local multi-container setup.
286+
- **P1 / M**: No CI/CD pipeline. Next action: Add GitHub Actions workflow for build, test, and Docker image push.
287+
- **P2 / S**: No monitoring or observability (metrics, health checks). Next action: Add Spring Boot Actuator and configure `/health` endpoint.
288+
289+
### Developer experience
290+
- **P1 / S**: No hot reload for backend. Next action: Ensure Spring Boot DevTools is configured (already in `build.gradle.kts`).
291+
- **P1 / S**: No pre-commit hooks for linting or formatting. Next action: Add Husky with `lint-staged` for frontend, Spotless for backend.
292+
- **P2 / S**: No contributing guidelines. Next action: Add `CONTRIBUTING.md` with PR process and code style.
293+
294+
## How this repository is useful
295+
296+
**Reusable patterns:**
297+
298+
1. **RESTful communication between Spring Boot and Next.js**: Clean separation of backend logic (Java) and frontend UI (TypeScript/React). CORS configuration example.
299+
2. **Chess engine logic**: `Chessboard.java` demonstrates move validation, check detection, and special move handling (en passant, castling, promotion). Adaptable for other turn-based board games.
300+
3. **React state management with hooks**: `Chessboard.tsx` shows useState for game state, async API calls, and conditional rendering (promotion modal).
301+
4. **DTO pattern**: Clear request/response objects (`ChessGameResponse`, `ChessboardMoveRequest`) for API contracts.
302+
303+
**Reusable components:**
304+
305+
- `ChessService.tsx`: Generic HTTP client pattern for Next.js API calls.
306+
- `Chessboard` and `ChessPiece` domain models: Transferable to other chess-related projects.
307+
308+
**What future projects can reuse:**
309+
310+
- The chess rule engine (`Chessboard.java`) can be extracted as a library for chess games, puzzles, or AI training.
311+
- The frontend chessboard UI (`Chessboard.tsx`, SVG assets) can be adapted for online multiplayer chess or chess tutoring apps.
312+
- The Spring Boot REST controller pattern is a template for stateful game APIs.
313+
314+
## Automation hooks
315+
316+
**Project type:** Full-stack web application (REST API + SPA)
317+
318+
**Primary domain:** Board games, chess engine, turn-based game logic
319+
320+
**Core entities:**
321+
- `ChessGame` (game state, turns, win conditions)
322+
- `Chessboard` (board representation, move validation)
323+
- `ChessPiece` (piece type, color, position)
324+
- `Position` (row, column coordinates)
325+
326+
**Extension points:**
327+
- **Add AI opponent**: Extend `ChessGame` with a move generator (e.g., minimax algorithm). Safe to add in `/backend/src/main/java/com/backend/ai`.
328+
- **Add multiplayer**: Replace in-memory game storage with a database and add WebSocket support for real-time updates. Requires changes in `ChessController` and `ChessGame`.
329+
- **Add move history**: Add a `List<Move>` to `ChessGame` to track all moves. Safe to add; does not break existing logic.
330+
- **Add themes/UI customization**: Modify CSS in `/frontend/src/app/globals.css` or add theme context in React.
331+
332+
**Areas safe to modify:**
333+
- `/backend/src/main/java/com/backend/util` — Add new utility methods
334+
- `/frontend/src/app/_client_components` — Add new UI components
335+
- `/frontend/public` — Add new SVG assets
336+
- `/backend/src/test` and `/frontend/src/app/_client_components/*.test.tsx` — Add more tests
337+
- `/backend/src/main/resources/application.properties` — Add Spring Boot configuration (e.g., logging, server port)
338+
339+
**Areas requiring caution and why:**
340+
- **`Chessboard.java` move validation logic**: Changes here can break game rules. Requires extensive testing (check, checkmate, en passant edge cases).
341+
- **`ChessController.java` in-memory game instance**: Changing to multi-game support requires major refactoring (e.g., game ID management, session handling).
342+
- **Frontend `ChessService` API URLs**: If backend URL changes, update `ChessService.tsx` line 8 and backend CORS config in `ChessController.java` line 16.
343+
- **Position coordinate system**: Backend uses 1-indexed rows (1-8) and columns (1-8). Frontend adjusts with offsets. Changing this affects both frontend and backend.
344+
345+
**Canonical commands:**
346+
347+
| Task | Command |
348+
|-----------------------|----------------------------------------------|
349+
| **Backend: Build** | `cd backend && ./gradlew build` |
350+
| **Backend: Test** | `cd backend && ./gradlew test` |
351+
| **Backend: Run** | `cd backend && ./gradlew bootRun` |
352+
| **Frontend: Install** | `cd frontend && npm install` |
353+
| **Frontend: Build** | `cd frontend && npm run build` |
354+
| **Frontend: Test** | `cd frontend && npm test` |
355+
| **Frontend: Run (dev)** | `cd frontend && npm run dev` |
356+
| **Frontend: Lint** | `cd frontend && npm run lint` |

backend/src/main/java/com/backend/controllers/ChessController.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,21 @@
1313

1414
import java.util.concurrent.atomic.AtomicLong;
1515

16+
/**
17+
* Problem: Need to expose chess game functionality via HTTP REST API for a web frontend.
18+
*
19+
* Goal: Provide endpoints for starting/ending games, making moves, querying valid moves,
20+
* and retrieving game state. Maintain single in-memory game instance per server.
21+
*
22+
* Approach: Spring Boot REST controller with GET/POST endpoints. Singleton game instance
23+
* stored as instance variable (lost on server restart). CORS configured for localhost:3000.
24+
* Delegates all game logic to ChessGame domain class.
25+
*
26+
* Time: O(1) for game state queries, O(n) for moves (delegated to ChessGame)
27+
* Space: O(1) per game (one game instance stored)
28+
*
29+
* Tags: rest-api, spring-boot, game-controller
30+
*/
1631
@CrossOrigin(origins = {"http://localhost:3000/", "http://localhost:3000"})
1732
@RestController
1833
public class ChessController {

backend/src/main/java/com/backend/domain/ChessGame.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,20 @@
77
import java.util.HashSet;
88
import java.util.Set;
99

10+
/**
11+
* Problem: Need to manage chess game state across multiple moves, track turn order,
12+
* captured pieces, and detect check/checkmate conditions.
13+
*
14+
* Goal: Provide a high-level game controller that coordinates move validation,
15+
* turn management, and win condition detection.
16+
*
17+
* Approach: Delegates move validation to Chessboard. Maintains game state (Free, Check, Checkmate),
18+
* current turn (White/Black), and sets of captured pieces. After each move, checks for
19+
* check and checkmate conditions for the next player.
20+
*
21+
* Time: O(n) per move where n is the number of pieces (for check/checkmate detection)
22+
* Space: O(1) additional space beyond the board representation
23+
*/
1024
public class ChessGame {
1125
private GameState gameState;
1226

0 commit comments

Comments
 (0)