Dev Plan - ryanelmore88/habits-adventure-frontend GitHub Wiki

Habits Adventure - Complete Development Plan

🚨 Critical Issues to Fix First

1. Remove Hardcoded IP Address

File: frontend/src/config.js

// Current issue: Hardcoded IP
export const BACKEND_URL = "http://192.168.0.76:8000/api";

// Solution: Use environment variable
export const BACKEND_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:8000/api";

2. Implement Authentication System

Priority: CRITICAL - No user isolation currently exists

  • Backend: Add JWT authentication with FastAPI
  • Frontend: Add login/register pages with protected routes
  • Database: Add User vertex and link Characters to Users

3. Fix Quest State Persistence

Current Issue: Quest progress is lost on page refresh

  • Store quest state in database (add QuestProgress vertex)
  • Create endpoints for saving/loading quest progress
  • Implement auto-save functionality

📋 Phase 1: Core Functionality (2-3 weeks)

1.1 Authentication & User Management

# backend/app/routers/auth.py
from fastapi import APIRouter, HTTPException, Depends
from fastapi.security import OAuth2PasswordBearer
import jwt

router = APIRouter(tags=["auth"])

@router.post("/register")
async def register(email: str, password: str):
    # Create user vertex in Gremlin
    # Hash password with bcrypt
    # Return JWT token

@router.post("/login")
async def login(email: str, password: str):
    # Verify credentials
    # Return JWT token

1.2 Quest System Improvements

Quick Quest Creation System

// frontend/src/components/QuestEditor/QuestEditor.jsx
const QuestEditor = () => {
    // Visual quest builder with:
    // - Drag-and-drop room connections
    // - Feature templates (combat, puzzle, treasure)
    // - JSON import/export for sharing quests
};

Backend Quest Storage

# backend/app/models/quest.py
def create_quest_template(quest_data):
    """Store quest templates in database"""
    query = (
        f"g.addV('QuestTemplate')"
        f".property('quest_id', '{quest_id}')"
        f".property('title', '{title}')"
        f".property('rooms', '{json.dumps(rooms)}')"
        f".property('created_by', '{user_id}')"
    )

1.3 Database Schema Updates

# New vertices and edges needed:
# User -[owns]-> Character
# Character -[hasProgress]-> QuestProgress
# Character -[hasInventory]-> Item
# QuestTemplate -[createdBy]-> User

🎮 Phase 2: Enhanced Gameplay (3-4 weeks)

2.1 Items & Equipment System

Item Categories

const itemTypes = {
    weapons: {
        // Affects damage rolls
        "rusty_sword": { bonus: 1, attribute: "strength" },
        "magic_staff": { bonus: 2, attribute: "intelligence" }
    },
    armor: {
        // Affects HP and defense
        "leather_armor": { hp_bonus: 5, defense: 1 },
        "plate_mail": { hp_bonus: 15, defense: 3 }
    },
    consumables: {
        // One-time use items
        "health_potion": { effect: "heal", value: 20 },
        "strength_elixir": { effect: "buff", attribute: "strength", duration: 3 }
    },
    quest_items: {
        // Special items for quest progression
        "golden_key": { unlocks: "treasure_room" },
        "ancient_tome": { reveals: "secret_passage" }
    }
};

Implementation Plan

  1. Database Schema:

    # Item vertex properties
    - item_id
    - name
    - type (weapon/armor/consumable/quest)
    - bonus_stats (JSON)
    - rarity (common/rare/epic/legendary)
    - value (for shop system)
  2. Character Equipment Slots:

    // frontend/src/components/Character/EquipmentSlots.jsx
    const equipmentSlots = {
        weapon: null,
        armor: null,
        accessory1: null,
        accessory2: null
    };
  3. Loot System Integration:

    • Add rarity-based drop tables
    • Quest-specific rewards
    • Random loot from combat victories

2.2 Enhanced Combat System

  • Add equipment bonuses to dice rolls
  • Implement status effects (poison, buff, debuff)
  • Create boss battles with special mechanics

2.3 Character Progression

  • Skill trees based on attributes
  • Unlockable abilities at certain levels
  • Prestige system for max-level characters

☁️ Phase 3: AWS Deployment (1-2 weeks)

3.1 Infrastructure Setup

AWS Services Architecture

# infrastructure/aws-setup.yml
Services:
  - Frontend: S3 + CloudFront
  - Backend: ECS Fargate or Lambda
  - Database: Amazon Neptune
  - Auth: Cognito (optional)
  - Storage: S3 for character images

Deployment Scripts

# deploy/deploy-backend.sh
#!/bin/bash
# Build Docker image
docker build -t habits-adventure-backend .

# Push to ECR
aws ecr get-login-password | docker login --username AWS --password-stdin
docker tag habits-adventure-backend:latest $ECR_URI:latest
docker push $ECR_URI:latest

# Update ECS service
aws ecs update-service --service habits-backend --force-new-deployment

3.2 CI/CD Pipeline

# .github/workflows/deploy.yml
name: Deploy to AWS
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v1
      - name: Deploy Backend
        run: ./deploy/deploy-backend.sh
      - name: Deploy Frontend
        run: |
          cd frontend
          npm run build
          aws s3 sync dist/ s3://$BUCKET_NAME
          aws cloudfront create-invalidation --distribution-id $CF_ID --paths "/*"

💰 Phase 4: Monetization Strategy (2-3 weeks)

4.1 Freemium Model

Free Tier

  • 3 characters max
  • Basic quests
  • Limited inventory space
  • Standard dice skins

Premium Tier ($4.99/month)

  • Unlimited characters
  • Premium quest library
  • Expanded inventory
  • Custom dice skins
  • Character appearance customization
  • Priority support

Premium+ Tier ($9.99/month)

  • Everything in Premium
  • Quest creator/sharing
  • Early access features
  • Exclusive items/equipment
  • Monthly premium currency

4.2 In-App Purchases

const iapItems = {
    currency: {
        "100_gems": { price: 0.99, gems: 100 },
        "550_gems": { price: 4.99, gems: 550 }, // 10% bonus
        "1200_gems": { price: 9.99, gems: 1200 } // 20% bonus
    },
    cosmetics: {
        "dice_pack_neon": { price: 2.99, type: "dice_skin" },
        "character_outfit_knight": { price: 3.99, type: "outfit" }
    },
    boosts: {
        "xp_boost_1day": { price: 1.99, duration: 24 },
        "loot_boost_1week": { price: 4.99, duration: 168 }
    }
};

4.3 Payment Integration

  • Stripe for web payments
  • Apple/Google IAP for mobile
  • Subscription management with webhook handling

📱 Phase 5: iPhone App Development (4-6 weeks)

5.1 Technology Options

Option A: React Native (Recommended)

Pros: Reuse existing React components, single codebase Cons: Some native features require bridging

// Convert existing components to React Native
// frontend/src/components/Character/CharacterCard.jsx → 
// mobile/src/components/Character/CharacterCard.tsx

import { View, Text, Image, TouchableOpacity } from 'react-native';

const CharacterCard = ({ character, onPress }) => {
    return (
        <TouchableOpacity onPress={onPress}>
            <View style={styles.card}>
                <Image source={{ uri: character.imageUrl }} style={styles.avatar} />
                <Text style={styles.name}>{character.name}</Text>
            </View>
        </TouchableOpacity>
    );
};

Option B: Capacitor/Ionic

Pros: Minimal code changes, web-like development Cons: Performance limitations, larger app size

5.2 Mobile-Specific Features

  1. Push Notifications

    • Habit reminders
    • Quest completion alerts
    • Daily login rewards
  2. Offline Mode

    • Cache character data
    • Queue habit completions
    • Sync when online
  3. Native Integrations

    • Apple Health for fitness habits
    • Calendar for scheduling
    • Widgets for quick habit tracking

5.3 App Store Preparation

# mobile/app-store-config.yml
App Information:
  name: "Habits Adventure"
  category: "Health & Fitness / Games"
  age_rating: "4+"
  
Required Assets:
  - App Icon (1024x1024)
  - Screenshots (6.5", 5.5" displays)
  - Preview Video (15-30 seconds)
  - Description (4000 chars max)
  
Review Guidelines:
  - Implement parental controls
  - Clear privacy policy
  - Secure payment handling
  - No gambling mechanics

🚀 Quick Wins (Can implement immediately)

1. Environment Variables

// frontend/.env
VITE_API_BASE_URL=http://localhost:8000/api
VITE_ENABLE_ANALYTICS=false
VITE_STRIPE_PUBLIC_KEY=pk_test_...

2. Error Handling

// frontend/src/utils/errorHandler.js
export const handleApiError = (error) => {
    if (error.response?.status === 401) {
        // Redirect to login
        window.location.href = '/login';
    } else if (error.response?.status === 500) {
        // Show user-friendly error
        toast.error('Something went wrong. Please try again.');
    }
    // Log to error tracking service
    console.error('API Error:', error);
};

3. Loading States

// frontend/src/hooks/useAsyncState.js
export const useAsyncState = (asyncFunction) => {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [data, setData] = useState(null);
    
    const execute = async (...params) => {
        setLoading(true);
        try {
            const result = await asyncFunction(...params);
            setData(result);
        } catch (err) {
            setError(err);
        } finally {
            setLoading(false);
        }
    };
    
    return { loading, error, data, execute };
};

📊 Development Timeline

Month 1

  • Week 1-2: Authentication & Critical Fixes
  • Week 3-4: Quest System Improvements

Month 2

  • Week 1-2: Items & Equipment System
  • Week 3-4: AWS Deployment Setup

Month 3

  • Week 1-2: Monetization Implementation
  • Week 3-4: Mobile App MVP

Month 4

  • Week 1-2: Polish & Bug Fixes
  • Week 3-4: App Store Submission

🎯 Success Metrics

  1. Technical Health

    • 0 critical security issues
    • <3s page load time
    • 99.9% uptime
  2. User Engagement

    • Daily active users
    • Habit completion rate
    • Average session duration
  3. Monetization

    • Conversion rate to premium
    • Average revenue per user
    • Subscription retention rate

🔧 Development Best Practices

  1. Use Feature Flags

    if (features.EQUIPMENT_SYSTEM_ENABLED) {
        // Show equipment UI
    }
  2. Implement Logging

    import logging
    logger = logging.getLogger(__name__)
    logger.info(f"Character {character_id} completed quest {quest_id}")
  3. Add Analytics

    analytics.track('Quest Started', {
        questId: quest.id,
        difficulty: quest.difficulty,
        characterLevel: character.level
    });

This plan provides a clear roadmap to transform Habits Adventure from a prototype into a production-ready, monetizable mobile app. Focus on Phase 1 first to establish a solid foundation, then iterate based on user feedback.

⚠️ **GitHub.com Fallback** ⚠️