PROJECT OVERVIEW:
Create a single-page web application (SPA) for a novel chess variant called 1D Chess. This game simplifies the traditional chess experience by constraining all pieces to a single dimension (a line). The application aims to provide an engaging platform for users to play against an AI, learn the unique rules and strategies of 1D Chess, and explore its mathematical underpinnings, inspired by Martin Gardner's "Mathematical Games" column. The core value proposition is offering a mentally stimulating yet accessible strategy game that is easy to learn but challenging to master.
TECH STACK:
- **Frontend Framework**: React (using Vite for fast development setup)
- **Styling**: Tailwind CSS for utility-first styling and rapid UI development.
- **State Management**: Zustand for efficient and simple global state management.
- **Routing**: React Router DOM (if multiple "pages" or views are considered, though for SPA minimal routing might be needed).
- **Animation Library**: Framer Motion for smooth and declarative animations.
CORE FEATURES:
1. **1D Chess Game Board**:
- **User Flow**: Upon loading the app, the user sees the 1D chessboard, representing a single row of squares. The initial state displays the pieces in their starting positions (e.g., White King, Knight, Rook on one side; Black King, Knight, Rook on the other). The user can interact with the board to make their moves.
- **Details**: The board will be a horizontal strip. Squares will be clearly delineated. Pieces will have distinct visual representations. A visual indicator will show the currently selected piece and valid moves.
2. **AI Opponent**:
- **User Flow**: The user selects "Play vs AI." The AI will make its moves after the user completes theirs. The difficulty of the AI should be adjustable (e.g., Easy, Medium, Hard) in later iterations, but MVP will have a single, moderately challenging AI.
- **Details**: The AI will implement the rules of 1D Chess. It needs to understand piece movements, check, checkmate, stalemate, and repetition rules. For MVP, a simple minimax algorithm or a rule-based system can be used. A "thinking" indicator will be shown when the AI is calculating its move.
3. **Move Input & Validation**:
- **User Flow**: User clicks on a friendly piece. Valid moves for that piece are highlighted on the board. User clicks on a valid target square. The piece moves. If the move is illegal, an error message is briefly shown, and the piece returns to its original position.
- **Details**: The system must validate every move against the rules of 1D Chess (King: 1 square, Knight: 2 squares jump, Rook: linear). It must check for checks, checkmates, and stalemates after each move.
4. **Game Rules & Explanation**:
- **User Flow**: A dedicated "Rules" section or modal is accessible from the main interface. Clicking on a piece type or a game state (like "Checkmate") reveals detailed explanations and diagrams.
- **Details**: Clear, concise text explaining the objective, piece movements, win conditions (checkmate), and draw conditions (stalemate, threefold repetition, insufficient material). Visual aids (diagrams, short animations) are crucial.
5. **Undo Move**:
- **User Flow**: A dedicated "Undo" button is available. Clicking it reverts the game state to the previous turn (both player's and AI's move if applicable).
- **Details**: The application needs to maintain a history of game states. The undo functionality should restore the board, current player, and move history to the state before the last player's move.
UI/UX DESIGN:
- **Layout**: Single Page Application. A clean, minimalist layout. The main area will feature the 1D game board. A sidebar or top bar will contain game status (current player, turn count), action buttons (Undo, New Game, Rules), and potentially AI thinking indicator.
- **Color Palette**: A neutral and focused palette. Example:
- Backgrounds: Dark Gray (`#1f2937`)
- Board Squares: Light Gray (`#4b5563`) and slightly darker gray (`#374151`)
- Pieces: Distinct colors (e.g., White: `#e5e7eb`, Black: `#111827`, possibly with accent colors for selected pieces or checks).
- Text: White (`#ffffff`) or light gray for readability.
- Accent Colors: A subtle color for highlighting valid moves or active elements (e.g., a soft blue `#60a5fa`).
- **Typography**: A clean, readable sans-serif font like 'Inter' or 'Roboto'. Font sizes should be legible on various screen sizes.
- **Responsive Design**: The application must be fully responsive. The board should scale appropriately. On smaller screens, elements might stack vertically or be accessible via a menu.
- **Interactivity**: Clear visual feedback on hover states for pieces and buttons. Smooth transitions for piece movements.
COMPONENT BREAKDOWN:
1. `App.js` (or `main.jsx`): Root component. Sets up routing (if any), global layout, and state management provider.
- Props: None
- Responsibility: Application's entry point, main layout structure.
2. `Game.js`: Main game component. Manages game state, turn logic, and renders the board and controls.
- Props: `initialBoardState` (optional)
- Responsibility: Orchestrates the game flow, holds core game state (board, currentPlayer, history).
3. `Board.js`: Renders the 1D chessboard and all pieces.
- Props: `squares` (array representing board state), `selectedSquare` (index of selected piece), `validMoves` (array of valid move targets), `onSquareClick` (function to handle square clicks).
- Responsibility: Visual representation of the board and pieces. Handles user clicks on squares.
4. `Square.js`: Represents a single square on the 1D board.
- Props: `index` (square identifier), `piece` (piece type and color), `isSelected` (boolean), `isValidMove` (boolean), `onClick` (function).
- Responsibility: Renders a single square, displays piece if present, highlights if selected or valid move target.
5. `Piece.js`: Renders a single chess piece.
- Props: `type` (King, Knight, Rook), `color` (White, Black).
- Responsibility: Visual representation of a piece.
6. `Controls.js`: Contains game control buttons (New Game, Undo, Rules).
- Props: `onNewGame` (function), `onUndo` (function), `onShowRules` (function), `canUndo` (boolean).
- Responsibility: Provides user controls for managing the game.
7. `RulesModal.js`: Displays the game rules in a modal window.
- Props: `isOpen` (boolean), `onClose` (function).
- Responsibility: Presents rule information in a structured, accessible way.
8. `AIIcon.js`: Visual indicator for AI thinking.
- Props: `isThinking` (boolean).
- Responsibility: Provides visual feedback during AI's turn.
DATA MODEL:
- **Game State (`Zustand` store)**:
```javascript
{
board: string[]; // Array representing pieces on squares. e.g., ['', 'wK', 'wN', 'wR', '', 'bK', 'bN', 'bR']
currentPlayer: 'white' | 'black';
gameHistory: {
board: string[];
currentPlayer: 'white' | 'black';
}[];
selectedPiece: { index: number; type: string; color: string } | null;
validMoves: number[];
isCheck: boolean;
isMate: boolean;
isStalemate: boolean;
// ... potentially other game status flags
}
```
- **Piece Representation**: String codes like 'wK' (white King), 'bN' (black Knight), 'wR' (white Rook).
- **`Mock Data Examples`**:
- Initial Board State: `['', 'wK', 'wN', 'wR', '', 'bK', 'bN', 'bR']` (Assuming a small 8-square board for simplicity)
- Move History Entry: `{ board: ['wK', 'wN', '', 'wR', '', 'bK', 'bN', 'bR'], currentPlayer: 'black' }`
- `validMoves`: `[2, 4, 6]` (Indices where the selected piece can move)
ANIMATIONS & INTERACTIONS:
- **Piece Movement**: Smooth transition animation (e.g., using Framer Motion's `AnimatePresence` and `motion.div`) when a piece moves from one square to another.
- **Hover Effects**: Subtle scale or background color change on pieces and buttons when hovered over.
- **Valid Move Highlighting**: Pieces and squares that are valid moves should have a distinct visual indicator (e.g., pulsating circle, color overlay) applied smoothly.
- **AI Thinking Indicator**: A simple animation (e.g., spinning icon, pulsing dots) to show the AI is processing its move.
- **Check/Checkmate Indication**: A clear visual cue (e.g., red border around the king, specific animation) when a king is in check or checkmated.
- **Loading States**: If any data needs to be fetched (e.g., for advanced AI), implement skeleton loaders or spinners.
EDGE CASES:
- **Empty Board/Initial State**: Ensure the game starts correctly with pieces in their initial positions.
- **No Valid Moves**: Handle cases where a player has no legal moves (leading to stalemate or checkmate).
- **Check Detection**: Accurately detect when a king is under attack.
- **Checkmate/Stalemate Logic**: Implement correct conditions for game end states.
- **Threefold Repetition**: Requires tracking board history. Implement logic to detect and declare a draw.
- **Insufficient Material**: Detect when checkmate is impossible (e.g., only kings left) and declare a draw.
- **User Input Errors**: Gracefully handle invalid clicks or moves. Provide clear feedback without crashing.
- **Accessibility (a11y)**: Use semantic HTML, ARIA attributes where necessary (e.g., for screen readers), ensure sufficient color contrast, and keyboard navigation support.
SAMPLE DATA:
1. `initialGameState`:
```json
{
board: ['', 'wK', 'wN', 'wR', '', 'bK', 'bN', 'bR'],
currentPlayer: 'white',
gameHistory: [],
selectedPiece: null,
validMoves: [],
isCheck: false,
isMate: false,
isStalemate: false
}
```
2. `boardStateAfterWhiteKnightMove`:
```json
{
board: ['', '', 'wK', 'wR', 'wN', 'bK', 'bN', 'bR'],
currentPlayer: 'black',
gameHistory: [{ board: ['', 'wK', 'wN', 'wR', '', 'bK', 'bN', 'bR'], currentPlayer: 'white' }],
selectedPiece: null,
validMoves: [],
isCheck: false,
isMate: false,
isStalemate: false
}
```
3. `boardStateWithCheck`:
```json
{
board: ['wR', '', '', 'wK', '', 'bN', 'bK', ''],
currentPlayer: 'black',
// ... history
isCheck: true // Black King is in check
}
```
4. `mockGameScenario_Checkmate`:
```json
{
board: ['', 'wK', '', '', '', 'bN', 'bR', 'bK'],
currentPlayer: 'white',
// ... history
isMate: true // Black King is checkmated
}
```
5. `mockGameScenario_Stalemate`:
```json
{
board: ['wK', '', 'wR', '', '', '', '', 'bK'],
currentPlayer: 'black',
// ... history
isStalemate: true // Black has no legal moves, not in check
}
```
6. `pieceInfo_Knight`:
`{ type: 'Knight', color: 'white', position: 2 }`
7. `validMovesForKnightAtPos2`:
`[0, 4, 5]`
8. `pieceInfo_King`:
`{ type: 'King', color: 'black', position: 7 }`
9. `aiThinkingIndicatorState`:
`{ isThinking: true }`
10. `rulesData`:
```json
{
king: { description: 'Moves one square in any direction.', movement: '1 square' },
knight: { description: 'Jumps 2 squares forward or backward.', movement: '2 squares (jump)' },
rook: { description: 'Moves any number of squares in a straight line.', movement: 'linear' },
checkmate: 'King is under attack and has no legal moves to escape.',
stalemate: 'Player has no legal moves, but is not in check (results in a draw).',
threeFoldRepetition: 'The same board position occurs three times (results in a draw).',
insufficientMaterial: 'Not enough pieces left to force a checkmate (results in a draw).'
}
```
DEPLOYMENT NOTES:
- **Build Tool**: Vite is recommended for its speed (`npm run build` or `yarn build`).
- **Environment Variables**: Use `.env` files for configuration (e.g., `VITE_AI_LEVEL` if AI difficulty is configurable).
- **Performance**: Optimize React components using `React.memo` where appropriate. Ensure efficient state updates with Zustand. Lazy load components if the app grows.
- **Hosting**: Static hosting platforms like Vercel, Netlify, or GitHub Pages are suitable for this SPA.
- **HTTPS**: Ensure deployment uses HTTPS for secure connections.
- **PWA Features**: Consider adding PWA capabilities (service workers, manifest file) for offline play and installability.