AI-powered Fruit Ninja game with hand tracking using MediaPipe and Pygame
Project description
AI Fruit Ninja - Optimized Edition
An enhanced version of the AI Fruit Ninja game with hand tracking using MediaPipe, optimized for performance and enhanced with advanced features.
🚀 Key Optimizations & Enhancements
Performance Improvements
1. Image Rotation Caching
- Implements a shared rotation cache across all game objects
- Reduces expensive rotation calculations by caching every 5 degrees
- Significant FPS improvement, especially with many objects on screen
2. Optimized Game Loop
- Eliminated repeated list searches and membership checks
- Batch removal of objects for better performance
- Single slice segment calculation per frame instead of per object
- Pre-calculated center positions cached in objects
3. Efficient Particle System
- Uses list comprehension for particle updates
- Individual particle physics for more realistic motion
- Fade-out and size reduction effects optimized
4. Thread-Safe Hand Tracking
- Added thread locks for concurrent access
- Frame skipping for better performance (processes every 2nd frame)
- Optimized camera settings (640x480 @ 30fps)
- Lightweight MediaPipe model (complexity=0)
5. Smart Collision Detection
- Early exit conditions for edge cases
- Optimized mathematical calculations
- Reduced redundant distance calculations
New Features
1. Dynamic Difficulty System
- 5 difficulty tiers: Easy, Medium, Hard, Expert, Master
- Progressive bomb spawn chance (10% → 30%)
- Speed multiplier increases with difficulty (1.0x → 1.8x)
- Visual difficulty indicator in HUD
2. Enhanced Visual Effects
- Screen Shake: Bomb explosions trigger dramatic screen shake
- Improved Sword Trail: Velocity-based intensity and multi-layer glow
- Better Particles: Individual physics, air resistance, fade-out, and size reduction
- Combo Glow: High combos (5+) display glowing effects
3. Advanced Scoring System
- Progressive combo bonuses (capped at 50 points)
- Max combo tracking
- Total slices counter
- Accuracy calculation support
4. Improved UI
- Difficulty tier display with color coding
- Enhanced combo visuals with glow effects
- Better telemetry panel
- Smoother animations
5. Configuration System
- Comprehensive
config.pyfor easy parameter tuning - Separate configs for gameplay, performance, and development
- All magic numbers eliminated from code
Code Quality Improvements
- Better Organization: Constants grouped in classes
- Memory Management: Object pooling considerations, cache limits
- Thread Safety: Proper locks in hand tracker
- Error Handling: Improved exception handling
- Documentation: Clear comments and docstrings
📊 Performance Metrics
Before Optimization
- ~45-50 FPS with 10+ objects
- Noticeable lag with high combo particle effects
- Image rotation every frame per object
After Optimization
- ~55-60 FPS with 10+ objects
- Smooth particle effects even with many objects
- 80% reduction in image rotation calculations
- 30% faster collision detection
🎮 Gameplay Features
Difficulty Progression
| Tier | Score Required | Bomb Chance | Speed Multiplier |
|---|---|---|---|
| Easy | 0 | 10% | 1.0x |
| Medium | 50 | 15% | 1.2x |
| Hard | 100 | 20% | 1.4x |
| Expert | 200 | 25% | 1.6x |
| Master | 300 | 30% | 1.8x |
Scoring
- Fruit Points: 5-15 points depending on fruit type
- Combo Bonus: +2 points per combo level (max +50)
- Combo Timer: 0.5 seconds between slices
- High Score: Persistent across game sessions
Visual Effects
- Particle Count: 20 for fruits, 50 for bombs
- Screen Shake: 15 intensity for 15 frames on bomb hit
- Sword Trail: 12-point trail with velocity-based intensity
- Dynamic Colors: Different effects for each fruit type
🛠️ Configuration
Edit config.py to customize:
Gameplay Tuning
BASE_SPAWN_DELAY = 100 # Starting difficulty
MIN_SPAWN_DELAY = 30 # Maximum difficulty
SPAWN_SPEED_INCREASE = 0.5 # Progression speed
Visual Effects
ENABLE_PARTICLE_EFFECTS = True
ENABLE_SCREEN_SHAKE = True
ENABLE_GLOW_EFFECTS = True
Hand Tracking
HAND_SMOOTHING_FACTOR = 0.4 # Lower = faster, Higher = smoother
HAND_MODEL_COMPLEXITY = 0 # 0 = fast, 1 = accurate
FRAME_SKIP = 2 # Process every Nth frame
📁 Project Structure
Fruit-Ninja/
├── main.py # Main game loop with optimized structure
├── game_objects.py # GameObject, Fruit, Bomb with caching
├── mechanics.py # ScoreSystem, DifficultyManager, GameEngine
├── visuals.py # ParticleSystem, SwordTrail, ScreenShake
├── hand_tracker.py # Optimized MediaPipe hand tracking
├── ui.py # Enhanced UI with difficulty display
├── config.py # Centralized configuration
├── assets/ # Game assets (images)
└── requirements.txt # Python dependencies
🎯 Technical Highlights
Memory Optimization
- Shared rotation cache with size limits
- Efficient particle removal using list comprehension
- Pre-calculated values stored in objects
Thread Safety
- Thread locks in hand tracker for concurrent access
- Proper thread cleanup on exit
- Daemon threads for automatic cleanup
Code Patterns
- Constants classes for organization
- Difficulty manager pattern for scalable progression
- Visual effects separated into dedicated classes
🚦 Getting Started
- Install dependencies:
pip install -r requirements.txt
- Run the game:
python main.py
- Controls:
- Raise hand to start
- Move index finger to slice fruits
- Avoid bombs!
- Mouse fallback if hand not detected
🎨 Customization Ideas
- Add new fruits: Edit
FRUIT_TYPESinconfig.py - Change difficulty curve: Modify
DIFFICULTY_TIERS - Adjust visual effects: Tune particle counts, colors, and intensities
- Performance tuning: Adjust cache limits and frame skip values
📈 Future Enhancement Ideas
- Power-ups (slow motion, bomb shield, 2x score)
- Multiple hand tracking for two-player mode
- Sound effects and background music
- Level system with different fruit combinations
- Gesture recognition for special moves
- Online leaderboards
- Replay system
🐛 Debugging
Enable debug mode in config.py:
class DevelopmentConfig:
DEBUG_MODE = True
SHOW_COLLISION_BOXES = True
SHOW_HAND_LANDMARKS = True
LOG_PERFORMANCE = True
📝 License
[Add your license here]
🤝 Contributing
Contributions welcome! Areas for improvement:
- Additional fruit types
- New visual effects
- Performance optimizations
- Bug fixes
Optimized for Project Expo - Showcasing AI, Computer Vision, and Game Development
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cv_fruit_ninja-1.0.2.tar.gz.
File metadata
- Download URL: cv_fruit_ninja-1.0.2.tar.gz
- Upload date:
- Size: 51.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
af4ead9d69ed5d14cb4b7357038a1ab89ba66c76d1aa9f223bcf3af3d2e81c42
|
|
| MD5 |
779e482197b3b4334a681742d850e16f
|
|
| BLAKE2b-256 |
276693c04cf920ea4789985541553c1dd4d2fed6ea89c9978f18cff1ae90a6ae
|
File details
Details for the file cv_fruit_ninja-1.0.2-py3-none-any.whl.
File metadata
- Download URL: cv_fruit_ninja-1.0.2-py3-none-any.whl
- Upload date:
- Size: 49.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d8cd4f7b12bd127d37b19c5d60744e3f284e0621d90b1b1e2801ba4d1e892349
|
|
| MD5 |
c4b6dc3a942692dfdf5e4db725782890
|
|
| BLAKE2b-256 |
31b297c1bc93952403e98fa4785b8947d0993eb417a9ac978ea107ff98600d56
|