Match My Mind Game - Complete API Guide

Step-by-step API documentation for iOS developers - Build the complete game flow

🚀 Quick Start - Game Flow Overview

Base URL for ALL Endpoints

/api/games/match-my-mind

Game Flow Summary

1️⃣
Get Categories

Show category selection

2️⃣
Create/Join Game

Start or join with code

3️⃣
Check Status

Know what to do next

4️⃣
Play & Results

Answer & see results

📋 Step-by-Step Implementation Guide

0Check for Current Game with Partner (NEW!)

🔥 IMPORTANT: Partner Integration

The game now automatically works with paired partners! No more game codes needed between partners.

🌐 API Endpoint

GET /api/games/match-my-mind?action=current_game&userId=USER_ID

📤 Request

Replace USER_ID with the current user's ID

// Swift Example
let url = "(baseURL)?action=current_game&userId=(currentUserId)"
let request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"

📥 Response

// If user has active game with partner:
{
  "success": true,
  "currentGame": {
    "_id": "session_abc123",
    "categoryId": "cat_relationship",
    "player1Id": "user_123",
    "player2Id": "user_456",  // Partner automatically added
    "gameCode": "XYZ789",
    "status": "player1_answering_self",
    "category": {
      "name": "Relationship Milestones",
      "icon": "💕"
    },
    "partnerId": "user_456"
  }
}

// If no active game:
{
  "success": true,
  "currentGame": null
}
💡 What to do with this:

Call this FIRST when app opens. If currentGame exists, go directly to Step 3 (game_status). If null, show category selection (Step 1).

1Get All Categories

🌐 API Endpoint

GET /api/games/match-my-mind?action=categories

📤 Request

No body required - simple GET request

// Swift Example
let url = "(baseURL)?action=categories"
let request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"

📥 Response

{
  "success": true,
  "categories": [
    {
      "_id": "cat_relationship",
      "name": "Relationship Milestones",
      "description": "Remember the little (and big) things",
      "icon": "💕",
      "color": "#FF6B9D",
      "isActive": true
    },
    {
      "_id": "cat_foodie",
      "name": "Foodie Fun", 
      "description": "Discover each other's tastes",
      "icon": "🍕",
      "color": "#FFD93D",
      "isActive": true
    }
    // ... 8 more categories
  ]
}
💡 What to do with this:

Display categories in a grid. User selects one to start the game.

2Create New Game

🌐 API Endpoint

POST /api/games/match-my-mind

📤 Request Body

{
  "action": "create_game",
  "categoryId": "cat_relationship",  // From step 1
  "playerId": "user_123"            // Current user ID
}

📥 Response

{
  "success": true,
  "gameSession": {
    "gameSessionId": "session_abc123",
    "gameCode": "XYZ789"  // Share this with partner!
  },
  "message": "Game created successfully!"
}
💡 What to do with this:

Save gameSessionId. Display gameCode for partner to join. Immediately go to step 3.

2BJoin Existing Game (Alternative to Step 2)

🌐 API Endpoint

POST /api/games/match-my-mind

📤 Request Body

{
  "action": "join_game",
  "gameCode": "XYZ789",     // Code from partner
  "playerId": "user_456"    // Current user ID
}

📥 Response

{
  "success": true,
  "gameSessionId": "session_abc123",
  "message": "Successfully joined the game!"
}
💡 What to do with this:

Save gameSessionId. Go directly to step 3 to check what to do next.

3Check Game Status (Most Important!)

🔥 Call this after EVERY action! This tells you exactly what screen to show.

🌐 API Endpoint

GET /api/games/match-my-mind?action=game_status&gameSessionId=session_abc123&playerId=user_123

📥 Response

{
  "success": true,
  "gameStatus": {
    "currentAction": "answer_for_self",     // What should player do?
    "canProceed": true,                     // Can they take action?
    "showResults": false,                   // Show results screen?
    "hasPartner": false,                    // Partner joined yet?
    "totalQuestions": 10,
    "myProgress": {
      "selfAnswersCompleted": 0,
      "guessAnswersCompleted": 0,
      "selfComplete": false,
      "guessComplete": false
    },
    "partnerProgress": {
      "selfAnswersCompleted": 0,
      "guessAnswersCompleted": 0,
      "selfComplete": false,
      "guessComplete": false
    },
    "gameCode": "XYZ789"
  }
}

🎯 currentAction Values & What To Do

"answer_for_self" → Show questions, let user answer about themselves
"wait_for_partner_self" → Partner hasn't answered yet. Show "My Answers" screen (Step 4A)
"answer_for_partner" → Show questions, let user guess partner's answers
"wait_for_partner_guess" → Waiting for partner to finish guessing
"game_completed" → Show final results screen (Step 5)
💡 Implementation:

Use currentAction to determine which screen to show. Call this API after every user action.

4Get Questions for Category

🌐 API Endpoint

GET /api/games/match-my-mind/categories?categoryId=cat_relationship

📥 Response

{
  "success": true,
  "questions": [
    {
      "_id": "q1",
      "questionText": "What makes me feel most loved in a relationship?",
      "options": [
        "Receiving thoughtful gifts",
        "Spending quality time together", 
        "Hearing words of affirmation",
        "Physical touch, like hugs"
      ],
      "order": 1
    },
    {
      "_id": "q2",
      "questionText": "How do I prefer to resolve conflicts?",
      "options": [
        "Talk it through immediately",
        "Take time to cool down first",
        "Write down my thoughts first", 
        "Physical comfort then discussion"
      ],
      "order": 2
    }
    // ... 8 more questions
  ],
  "total": 10
}
💡 What to do with this:

Display questions one by one. Use the order field to show them in sequence.

4AShow My Answers (When Waiting for Partner)

🌐 API Endpoint

GET /api/games/match-my-mind?action=my_answers&gameSessionId=session_abc123&playerId=user_123

📥 Response

{
  "success": true,
  "myAnswers": {
    "categoryName": "Relationship Milestones",
    "totalQuestions": 10,
    "answeredQuestions": 10,
    "questionsWithAnswers": [
      {
        "question": "What makes me feel most loved?",
        "options": ["Gifts", "Time", "Words", "Touch"],
        "myAnswer": "Spending quality time together",
        "answeredAt": 1640995200000
      },
      {
        "question": "How do I show affection?", 
        "options": ["Actions", "Time", "Words", "Touch"],
        "myAnswer": "Physical touch, like hugs",
        "answeredAt": 1640995230000
      }
      // ... all 10 questions with player's answers
    ]
  }
}
💡 When to use this:

When currentAction is "wait_for_partner_self". Show player their answers + "Share code XYZ789 with your partner" message.

4BSubmit Answer

🌐 API Endpoint

POST /api/games/match-my-mind

📤 Request Body

{
  "action": "submit_answer",
  "gameSessionId": "session_abc123",
  "playerId": "user_123",
  "questionId": "q1",
  "selectedOption": "Spending quality time together",
  "answerType": "self"  // "self" or "guess_partner"
}

📥 Response

{
  "success": true,
  "result": {
    "newStatus": "player1_answering_self"
  },
  "message": "Answer submitted successfully!"
}
💡 After submitting each answer:

Call Step 3 (game_status) again to see what to do next. answerType: "self" when answering about yourself, "guess_partner" when guessing partner's answers.

👥How Partners See Each Other's Answers (CRITICAL!)

🔥 FIXED: Partners Can Now See Each Other's Progress

The system now ensures both partners are in the SAME game session, so they can see each other's answers in real-time.

🎯 How It Works Now

1. Automatic Partner Pairing: When you create a game, your paired partner is automatically added to the same game session
2. Shared Game Session: Both partners use the same gameSessionId, so all answers are visible to both
3. Real-time Progress: Use game_status API to see partner's progress (selfAnswersCompleted, guessAnswersCompleted)
4. No Duplicate Answers: Players can update their answers but can't create multiple entries

📱 Implementation for Developers

// 1. Check partner progress in real-time
func checkPartnerProgress() async {
    let status = try await getGameStatus(gameSessionId: currentGameId, playerId: currentUserId)
    
    // Show partner's progress
    let partnerSelfComplete = status.gameStatus.partnerProgress.selfComplete
    let partnerGuessComplete = status.gameStatus.partnerProgress.guessComplete
    
    // Update UI to show partner status
    updatePartnerProgressUI(
        selfAnswers: status.gameStatus.partnerProgress.selfAnswersCompleted,
        guessAnswers: status.gameStatus.partnerProgress.guessAnswersCompleted,
        isWaiting: !status.gameStatus.canProceed
    )
}

// 2. Show waiting screen with partner's progress
func showWaitingScreen() async {
    // Get my answers to show while waiting
    let myAnswers = try await getMyAnswers(gameSessionId: currentGameId, playerId: currentUserId)
    
    // Also get current status to show partner progress
    let status = try await getGameStatus(gameSessionId: currentGameId, playerId: currentUserId)
    
    // Display: "You've answered X/10 questions. Your partner has answered Y/10 questions."
    displayWaitingScreen(
        myAnswers: myAnswers,
        partnerProgress: status.gameStatus.partnerProgress
    )
}

🔄 Real-time Updates Pattern

Every 5-10 seconds while waiting: Call game_status to check if partner has made progress
After each answer submission: Call game_status to see if you can continue or need to wait
Show live progress: "Your partner is answering question 3/10..." based on partnerProgress data
💡 Key Benefits for Users:
  • • No more sharing game codes between partners
  • • Partners automatically see each other's progress
  • • Real-time updates on waiting screens
  • • No duplicate answers or multiple game sessions
  • • Seamless game experience between paired users

5Get Final Results

🌐 API Endpoint

GET /api/games/match-my-mind?action=game_comparison&gameSessionId=session_abc123&playerId=user_123

📥 Response

{
  "success": true,
  "comparison": {
    "categoryName": "Relationship Milestones",
    "totalQuestions": 10,
    "player1": {
      "id": "user_123",
      "name": "John",
      "score": 8,
      "isWinner": true
    },
    "player2": {
      "id": "user_456", 
      "name": "Jane",
      "score": 6,
      "isWinner": false
    },
    "isTie": false,
    "questionComparisons": [
      {
        "questionId": "q1",
        "questionText": "What makes me feel most loved?",
        "options": ["Gifts", "Time", "Words", "Touch"],
        "player1": {
          "selfAnswer": "Spending quality time together",
          "guessForPartner": "Hearing words of affirmation", 
          "correctGuess": true
        },
        "player2": {
          "selfAnswer": "Hearing words of affirmation",
          "guessForPartner": "Spending quality time together",
          "correctGuess": true
        }
      }
      // ... all 10 questions with comparison
    ],
    "gameCompletedAt": 1640995500000
  }
}
💡 When to use this:

When currentAction is "game_completed" or showResults is true. Display winner, scores, and question-by-question comparison.

✅ Implementation Checklist

Follow this exact order:

0. Call GET current_game API → Check if user has active game with partner
1. Call GET categories API → Show category grid (if no current game)
2. User selects category → Call POST create_game → Save gameSessionId & show gameCode
3. Call GET game_status → Check currentAction
4. If "answer_for_self" → Get questions → Show question screen
5. User answers → POST submit_answer → Go back to step 3
6. If "wait_for_partner_self" → Call GET my_answers → Show waiting screen
7. If "answer_for_partner" → Show questions for guessing partner's answers
8. If "game_completed" → Call GET game_comparison → Show results

🔄 Key Rule:

Always call game_status after every user action to know what screen to show next!

📱 Swift Implementation Example

class MatchMyMindService {
    private let baseURL = "https://your-api.com/api/games/match-my-mind"
    
    // Step 0: Check Current Game with Partner (NEW!)
    func getCurrentGame(userId: String) async throws -> CurrentGameResponse {
        let url = "(baseURL)?action=current_game&userId=(userId)"
        // ... networking code
    }
    
    // Step 1: Get Categories
    func getCategories() async throws -> CategoriesResponse {
        let url = "(baseURL)?action=categories"
        // ... networking code
    }
    
    // Step 2: Create Game
    func createGame(categoryId: String, playerId: String) async throws -> CreateGameResponse {
        let body = [
            "action": "create_game",
            "categoryId": categoryId,
            "playerId": playerId
        ]
        // ... POST request
    }
    
    // Step 3: Check Status (MOST IMPORTANT!)
    func getGameStatus(gameSessionId: String, playerId: String) async throws -> GameStatusResponse {
        let url = "(baseURL)?action=game_status&gameSessionId=(gameSessionId)&playerId=(playerId)"
        // ... networking code
    }
    
    // Step 4: Get Questions
    func getQuestions(categoryId: String) async throws -> QuestionsResponse {
        let url = "(baseURL)/categories?categoryId=(categoryId)"
        // ... networking code
    }
    
    // Step 4A: Get My Answers (waiting screen)
    func getMyAnswers(gameSessionId: String, playerId: String) async throws -> MyAnswersResponse {
        let url = "(baseURL)?action=my_answers&gameSessionId=(gameSessionId)&playerId=(playerId)"
        // ... networking code
    }
    
    // Step 4B: Submit Answer
    func submitAnswer(gameSessionId: String, playerId: String, questionId: String, 
                     selectedOption: String, answerType: String) async throws -> SubmitResponse {
        let body = [
            "action": "submit_answer",
            "gameSessionId": gameSessionId,
            "playerId": playerId,
            "questionId": questionId,
            "selectedOption": selectedOption,
            "answerType": answerType
        ]
        // ... POST request
    }
    
    // Step 5: Get Final Results
    func getGameComparison(gameSessionId: String, playerId: String) async throws -> ComparisonResponse {
        let url = "(baseURL)?action=game_comparison&gameSessionId=(gameSessionId)&playerId=(playerId)"
        // ... networking code
    }
}

// Usage in ViewController
class GameViewController: UIViewController {
    func viewDidLoad() {
        super.viewDidLoad()
        checkForCurrentGame()
    }
    
    // NEW: Check for existing game with partner first
    func checkForCurrentGame() {
        Task {
            let currentGame = try await gameService.getCurrentGame(userId: currentUserId)
            
            await MainActor.run {
                if let game = currentGame.currentGame {
                    // User has active game with partner - continue it
                    self.currentGameId = game._id
                    self.handleGameFlow()
                } else {
                    // No active game - show category selection
                    self.showCategorySelection()
                }
            }
        }
    }
    
    func handleGameFlow() {
        Task {
            // Always check status first!
            let status = try await gameService.getGameStatus(gameSessionId: currentGameId, playerId: currentUserId)
            
            await MainActor.run {
                switch status.gameStatus.currentAction {
                case "answer_for_self":
                    showQuestionScreen(answerType: "self")
                case "wait_for_partner_self":
                    showMyAnswersScreen()
                case "answer_for_partner": 
                    showQuestionScreen(answerType: "guess_partner")
                case "game_completed":
                    showResultsScreen()
                default:
                    break
                }
            }
        }
    }
    
    func onAnswerSubmitted() {
        // After submitting any answer, check status again!
        handleGameFlow()
    }
}

📚 Complete API Reference

📥 GET APIs (Read Data)

Get Current Game with Partner

NEW - Step 0
GET /api/games/match-my-mind?action=current_game&userId=...

🔥 Check if user has active game with their paired partner. Call this FIRST when app opens!

Get Categories

Step 1
GET /api/games/match-my-mind?action=categories

Fetch all 10 game categories for category selection screen

Check Game Status

CRITICAL
GET /api/games/match-my-mind?action=game_status&gameSessionId=...&playerId=...

🔥 Most important API! Tells you what screen to show next (answer_for_self, wait_for_partner_self, etc.)

Get Questions

Step 4
GET /api/games/match-my-mind/categories?categoryId=...

Get all 10 questions for selected category with multiple choice options

Get My Answers

Waiting Screen
GET /api/games/match-my-mind?action=my_answers&gameSessionId=...&playerId=...

Show player's own answers while waiting for partner to complete their self-answers

Get Game Comparison

Final Results
GET /api/games/match-my-mind?action=game_comparison&gameSessionId=...&playerId=...

Complete game results with scores, winner, and question-by-question comparison

Get Game Session

Optional
GET /api/games/match-my-mind?action=game_session&gameSessionId=...

Get detailed game session info (use game_status instead for flow control)

Get User Stats

Optional
GET /api/games/match-my-mind?action=user_stats&userId=...

Get player's game statistics (games played, won, best score, etc.)

📤 POST APIs (Send Data)

Create Game

Step 2
POST /api/games/match-my-mind
Body: { "action": "create_game", "categoryId": "...", "playerId": "..." }

Start a new game session and get gameCode to share with partner

Join Game

Step 2B
POST /api/games/match-my-mind
Body: { "action": "join_game", "gameCode": "...", "playerId": "..." }

Join an existing game using the game code from partner

Submit Answer

FREQUENT
POST /api/games/match-my-mind
Body: { "action": "submit_answer", "gameSessionId": "...", "playerId": "...", "questionId": "...", "selectedOption": "...", "answerType": "self|guess_partner" }

Submit each answer (self or guess_partner). Call game_status after each submission!

Seed Data

Admin Only
POST /api/games/match-my-mind
Body: { "action": "seed_data" }

Reset and populate all categories with 10 questions each (admin/testing only)

🔄 API Call Flow Summary

🎮 Game Setup Flow

0GET current_game (check partner game)
1GET categories (if no current game)
2POST create_game OR join_game
3GET game_status (check what to do)
4GET questions (if needed)

🎯 Gameplay Flow

5POST submit_answer (for each question)
6GET game_status (after each answer)
7GET my_answers (if waiting)
8GET game_comparison (final results)

🔑 Golden Rule: Always call GET game_status after every POST submit_answer to know what to do next!

❓ Frequently Asked Questions

Q: How do I know if my partner has answered?

Call the game_status API. Check partnerProgress.selfComplete - if true, partner has finished answering about themselves.

Q: When should I show "My Answers" screen?

When currentAction is "wait_for_partner_self". Use the my_answers API to get the player's answers and show them while they wait.

Q: Do I need to wait for partner to join before starting?

No! Players can start answering immediately. Partners can join anytime using the game code.

Q: What's the difference between "self" and "guess_partner" answerType?

"self" = answering about yourself. "guess_partner" = guessing how your partner answered about themselves.