Drive Car Game Development Guide
A comprehensive development assistant for the Drive & Park game built with React, Matter.js, GSAP, and Tailwind CSS. This skill enforces architectural best practices, performance optimization, and quality standards for 2D physics-based web games.
Instructions
1. Project Awareness & Context
**At the start of every conversation:**
Read `PLANNING.md` to understand architecture, goals, style, and constraintsCheck `TASK.md` before starting new tasks - add new tasks with descriptions and dates if not listedReview `DESIGN_SPEC.md` for UI/UX requirements and component specificationsRemember: all React development happens in the `parking-game/` subdirectory**Follow consistent patterns:**
Use naming conventions, file structure, and architecture patterns from `PLANNING.md`Maintain project organization and coding standards throughout2. Code Structure & Modularity
**Enforce strict file size limits:**
Never create files longer than 500 lines of codeWhen approaching limit, refactor by splitting into modules or helper files**Organize components by feature:**
```
src/
├── components/
│ ├── ui/ # Screens (MainMenu, LevelSelect, HUD)
│ ├── controls/ # Input (SteeringWheel, GearControls)
│ ├── game/ # Logic (GameCanvas, Car, ParkingSpot)
│ └── common/ # Shared (Button, Modal)
├── hooks/ # Custom React hooks
├── utils/ # Helper functions
├── data/ # Level configs & constants
└── styles/ # Global styles & Tailwind
```
**Component organization:**
Each complex component gets its own directory: - `ComponentName.jsx` - Main logic
- `ComponentName.module.css` - Specific styles (if needed beyond Tailwind)
- `index.js` - Export barrel file
Use clear, consistent named imports (prefer over default imports)Use environment variables via Vite's `import.meta.env`3. Styling & Design
**Tailwind CSS as primary solution:**
Follow design system from `DESIGN_SPEC.md` for colors, spacing, typographyMobile-first approach (320px minimum width)Breakpoints: `sm: 640px`, `md: 768px`, `lg: 1024px`, `xl: 1280px`Test on various screen sizes and devices**Animations:**
Use GSAP for complex animations (menu transitions, game intro/outro)Use CSS transitions for simple hover/focus statesAlways clean up GSAP timelines in `useEffect` cleanup functions**Accessibility (WCAG 2.1 AA):**
Ensure keyboard navigation for all interactive elementsUse semantic HTML and ARIA labelsProvide alternative text for visual indicators4. Game Development Best Practices
**Matter.js Physics:**
Never update Matter.js bodies directly in React state - use `useRef`Implement fixed timestep (16.67ms for 60 FPS) for consistent physicsClean up Matter.js world and bodies on component unmount**Performance Optimization:**
Pre-load and cache all game assets (sprites, sounds)Use `useMemo` and `useCallback` for expensive computationsImplement viewport culling for off-screen objectsMonitor FPS - target 60 FPS desktop, 30+ FPS mobile**State Management:**
Use React Context API for global state (game progress, settings)Use `useReducer` for complex state logic (game state machine)Persist important state to localStorage (level progress, settings)Separate game state from UI state**Level Data:**
Store level configurations as JSON files in `src/data/levels/`Each level defines: obstacles, parking spot, difficulty, time limitsValidate level data structure on load5. Testing & Reliability
**Component Testing (Vitest + @testing-library/react):**
Test user interactions (clicks, drags, keyboard input)Test responsive behavior at different viewportsMock external dependencies (Matter.js, GSAP, localStorage)**Game Logic Testing:**
Unit test physics calculations (car movement, collision detection, scoring)Test level completion conditionsTest edge cases (division by zero, boundary conditions)**Integration Testing:**
Test complete flows (start game → complete level → progress)Test state persistence across page refreshesTest error recovery (network failures, localStorage quota exceeded)**Manual Testing Checklist:**
Test on real mobile devices (iOS Safari, Android Chrome)Test touch controls with actual fingers, not mouse emulationTest on different screen sizes (phone, tablet, desktop)Test on different refresh rates (60Hz, 90Hz, 120Hz)Test with reduced motion settings enabledTest keyboard navigation for accessibility6. Task Completion
Mark completed tasks in `TASK.md` immediately after finishingAdd new sub-tasks/TODOs discovered during development to `TASK.md` under "Discovered During Work"Update task status with actual completion datesMove completed tasks to "Completed" section at bottom7. Code Style & Conventions
**JavaScript ES6+ with JSX:**
Use ESLint configuration from `eslint.config.js`2-space indentationSingle quotes for stringsSemicolons at end of statementsTrailing commas in objects/arrays**Naming Conventions:**
Components: PascalCase (`SteeringWheel.jsx`)Hooks: camelCase with "use" prefix (`useCarPhysics.js`)Utilities: camelCase (`calculateScore.js`)Constants: UPPER_SNAKE_CASE (`MAX_SPEED`)CSS classes: kebab-case or Tailwind utilities**Component Structure Template:**
```jsx
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
/**
* Brief component description
* @param {Object} props - Component props
* @param {string} props.name - Prop description
*/
const ComponentName = ({ name }) => {
// Hooks
const [state, setState] = useState(null);
// Effects
useEffect(() => {
// Effect logic
return () => {
// Cleanup
};
}, []);
// Event handlers
const handleClick = () => {
// Handler logic
};
// Render
return (
<div className="component-name">
{/* JSX */}
</div>
);
};
ComponentName.propTypes = {
name: PropTypes.string.isRequired,
};
export default ComponentName;
```
8. Documentation & Comments
**Update `README.md` when:**
New features are addedDependencies changeSetup steps are modifiedDeployment process changes**Code Comments:**
Add JSDoc comments for all components and functionsComment non-obvious code with explanations of "why", not "what"Use `// Reason:` prefix for important implementation decisionsAdd TODO comments: `// TODO: Add error boundary`9. AI Behavior Rules
Never assume missing context - ask questions if uncertainNever hallucinate libraries or packages - only use known, verified npm packagesAlways confirm file paths and module names exist before referencingNever delete or overwrite existing code unless explicitly instructed or part of task from `TASK.md`When suggesting new dependencies, explain why needed and check bundle size impactTest on real devices when possible, don't rely solely on browser DevTools emulation10. Development Workflow
**Starting Development:**
```bash
cd parking-game
npm install
npm run dev
Open http://localhost:5173
```
**Before Committing:**
```bash
npm run lint
npm run build
npm run preview
npm run test
Check for console errors/warnings
```
11. Deployment (GitHub Pages)
**Initial Setup (One-Time):**
```bash
git checkout --orphan gh-pages
echo "<html><body><h1>Site deploying...</h1></body></html>" > index.html
git add index.html
git commit -m "Initial gh-pages commit"
git push origin gh-pages
git checkout main
```
**Configure GitHub Pages:**
Repository Settings → Pages → Source: `gh-pages` branch**Update `vite.config.js`:**
```js
export default defineConfig({
base: '/drive-car/', // Replace with repo name
// ... other config
});
```
**Create `.github/workflows/deploy.yml`:**
```yaml
name: Deploy to GitHub Pages
on:
push:
branches: [ main ]
jobs:
build-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install and Build
working-directory: ./parking-game
run: |
npm ci
npm run build
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./parking-game/dist
```
12. Performance Targets
Bundle Size: < 500KB gzippedInitial Load: < 3 seconds on 4GFPS: 60 on desktop, 30+ on mobileLighthouse Score: 90+ across all metricsFirst Contentful Paint: < 1.5sTime to Interactive: < 3.5s13. Common Gotchas
1. **Canvas DPI Scaling**: Always account for `devicePixelRatio` when sizing canvas
2. **Touch Event Bubbling**: Use `preventDefault()` to stop page scrolling during gameplay
3. **GSAP Cleanup**: Always kill tweens in cleanup functions to prevent memory leaks
4. **Matter.js State**: Never store Matter.js bodies in React state - use refs
5. **localStorage Quota**: Implement error handling for quota exceeded errors
6. **Vite Asset Imports**: Use `new URL('./asset.png', import.meta.url).href` for dynamic imports
7. **GitHub Pages SPA Routing**: Add 404.html that redirects to index.html
8. **Mobile Safari Viewport**: Use `viewport-fit=cover` and account for safe areas on notched devices
Technology Stack
React 18 (UI framework)Vite (Build tool)Tailwind CSS (Styling)Matter.js (2D physics)GSAP (Animation)ESLint (Linting)Vitest + @testing-library/react (Testing)Usage Example
When user says: "Add a new level with obstacles"
1. Check `TASK.md` - add task if not listed
2. Review `DESIGN_SPEC.md` for level UI requirements
3. Create level JSON in `src/data/levels/level-X.json`
4. Ensure file stays under 500 lines
5. Implement Matter.js physics using refs, not state
6. Add unit tests for collision detection
7. Test on mobile device with real touch input
8. Update `TASK.md` marking task complete
9. Run pre-commit checks (lint, build, preview)