Meaning Full Power - Game Mechanics Architecture
This document provides a comprehensive breakdown of all game mechanics, their interfaces, dependencies, and how they interconnect. Use this as a reference when developing or debugging individual components.
Full Public Reader
Meaning Full Power - Game Mechanics Architecture
Complete Modular System Reference
This document provides a comprehensive breakdown of all game mechanics, their interfaces, dependencies, and how they interconnect. Use this as a reference when developing or debugging individual components.
---
Table of Contents
1. [System Overview](#1-system-overview)
2. [Core Data Models](#2-core-data-models)
3. [Battle Engine](#3-battle-engine)
4. [Theme System](#4-theme-system)
5. [Ability Engine](#5-ability-engine)
6. [Deck System](#6-deck-system)
7. [Persistence Layer](#7-persistence-layer)
8. [Victory Conditions](#8-victory-conditions)
9. [AI Opponent System](#9-ai-opponent-system)
10. [Game Rules Reference](#10-game-rules-reference)
11. [Component Dependency Graph](#11-component-dependency-graph)
12. [Implementation Checklist](#12-implementation-checklist)
---
1. System Overview
Architecture Pattern
┌─────────────────────────────────────────────────────────────────┐
│ PRESENTATION │
│ MainHubView │ BattleArenaView │ GrimoireView │ DeckBuilderView │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ VIEW MODELS │
│ BattleViewModel │ DeckViewModel │ CollectionViewModel │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ GAME LOGIC LAYER │
│ AbilityEngine │ ThemeInteraction │ VictoryCalculator │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ DATA LAYER │
│ Card │ Deck │ Battle │ User │ Theme │ GameRules │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ PERSISTENCE LAYER │
│ PersistenceManager │ SwiftData Models │ Sync Queue │
└─────────────────────────────────────────────────────────────────┘File Structure
Models/
├── Card.swift # Card, CardType, Rarity, CardAbility, UserCard, Grimoire
├── Deck.swift # Deck, DeckBuilder
├── Battle.swift # BattleType, BattlePhase, VictoryCondition, BattleState
├── Theme.swift # Theme enum, ThemeInteraction
├── User.swift # User, PlayStyle, EmotionalProfile, UserStats
├── GameRules.swift # All game constants and rules
├── PersistentModels.swift # SwiftData @Model classes
Services/
├── AbilityEngine.swift # Card ability execution
├── PersistenceManager.swift # Data persistence
├── TutorialManager.swift # Tutorial flow
├── AIOrchestrator.swift # AI content generation---
2. Core Data Models
### 2.1 Card Model
File: `Models/Card.swift`
struct Card: Identifiable, Codable, Hashable {
let id: String
let page: Int // 1-127 (book page number)
let title: String
let type: CardType
let rarity: Rarity
// Content
let excerpt: String // Display text
let fullText: String // Complete text
let reflectionQuestion: String? // For reflection cards
// Themes (core gameplay)
let primaryTheme: Theme
let secondaryThemes: [Theme]
// Gameplay Attributes
let emotionalPower: Int // 10-100
let wisdomCost: Int // 0-5
let abilities: [CardAbility]
// Visual Assets
let designPageURL: String?
let illustrationURL: String?
let illustrationWithTextURL: String?
// Metadata
let chapterTitle: String?
let isChapterTitle: Bool
let language: String
}Key Computed Properties:
- `effectivePower`: Base power × type multiplier
- `allThemes`: Primary + secondary themes
- `qrCodeURL`: Deep link for physical card scanning
2.2 Card Types
| Type | Power Multiplier | Count | Description |
|---|---|---|---|
| Wisdom | 1.0x | ~85 | Prose passages |
| Poem | 1.5x | 14 | Rare, powerful |
| Reflection | 1.2x | 28 | Interactive questions |
| Theme | 1.3x | 12 | Pure elemental cards |
| Custom | 1.0x | Unlimited | AI-generated |
2.3 Rarity System
| Rarity | Drop Rate | Border Color | Max Copies/Deck |
|---|---|---|---|
| Common | 60 | ||
| Uncommon | 25 | ||
| Rare | 10 | ||
| Epic | 4 | ||
| Legendary | 1 |
2.4 Card Abilities
struct CardAbility: Codable, Identifiable {
let id: String
let name: String
let description: String
let triggerType: AbilityTrigger
let effect: AbilityEffect
}
enum AbilityTrigger: String, Codable {
case onPlay // When card is played
case onDiscard // When card is discarded
case passive // Always active
case resonance // When themes combine
case reflection // When question is answered
}
enum AbilityEffect: String, Codable {
case drawCard // Draw 1 card
case gainWisdom // +1-2 wisdom
case emotionalGrowth // +15-20 growth
case themeBonus // +3 per matching theme
case healingAura // +5 growth, +1 wisdom
case resonanceBoost // 1.5x synergy bonus
}---
3. Battle Engine
### 3.1 Battle Flow
File: `Models/Battle.swift`
SETUP → DRAW → WISDOM → PLAY → RESONANCE → REFLECTION → GROWTH → (repeat or ENDED)3.2 Battle Phases
| Phase | Action | Duration |
|---|---|---|
| SETUP | Shuffle decks, draw 5 cards | Once |
| DRAW | Draw 1 card from deck | Per turn |
| WISDOM | Regenerate +2 wisdom (max 5) | Per turn |
| PLAY | Spend wisdom to play cards | Player action |
| RESONANCE | Calculate theme synergies/counters | Automatic |
| REFLECTION | Answer reflection questions | Optional |
| GROWTH | Award emotional growth points | Automatic |
| ENDED | Declare winner | Once |
3.3 Battle State
struct BattleState: Codable {
let battleId: String
var turn: Int // Current turn number
var phase: BattlePhase // Current phase
var currentPlayerId: String // Whose turn
var player1: PlayerBattleState
var player2: PlayerBattleState
var resonanceZone: [Card] // Cards resolving effects
var turnTimer: TimeInterval // 90 seconds per turn
var lastAction: BattleAction?
var actionLog: [String]
}3.4 Player Battle State
struct PlayerBattleState: Codable, Identifiable {
let id: String
let oderId: String
let nickname: String
let avatarURL: String?
var hand: [Card] // Cards in hand (max 10)
var deckCards: [String] // Remaining deck card IDs
var discardPile: [Card] // Discarded cards
var activeCards: [Card] // Cards in play zone
var emotionalState: EmotionalState // Growth tracking
}3.5 Emotional State (Victory Tracker)
struct EmotionalState: Codable {
var growthPoints: Int = 0 // Target: 100 for victory
var wisdomPool: Int = 3 // Mana system (max 5)
var maxWisdom: Int = 5
var resonanceMultiplier: Double = 1.0 // Synergy bonus
var activeThemes: Set<Theme> = [] // Themes played this game
var reflectionBonus: Int = 0 // From answering questions
var resonanceComboCount: Int = 0 // Target: 5 for victory
// Victory checks
var isEnlightened: Bool { growthPoints >= 100 }
var hasAllThemes: Bool { activeThemes.count >= 12 }
var hasResonanceVictory: Bool { resonanceComboCount >= 5 }
}3.6 Battle Actions
enum BattleAction: Codable {
case drawCard
case playCard(cardId: String)
case activateAbility(cardId: String, abilityId: String)
case answerReflection(cardId: String, answer: String)
case endTurn
case surrender
}---
4. Theme System
### 4.1 The 12 Themes
File: `Models/Theme.swift`
| Theme | Icon | Color | Rarity Weight |
|---|---|---|---|
| Time | clock.fill | #3B82F6 | 1.00 (most common) |
| Hope | star.fill | #A855F7 | 0.57 |
| Passion | flame.fill | #EF4444 | 0.45 |
| Fulfillment | leaf.fill | #22C55E | 0.45 |
| Confidence | sun.max.fill | #F97316 | 0.40 |
| Healing | heart.fill | #10B981 | 0.40 |
| Potential | arrow.up.circle.fill | #60A5FA | 0.40 |
| Transcendence | sparkles | #8B5CF6 | 0.25 |
| Freedom | wind | #14B8A6 | 0.23 |
| Equality | scale.3d | #A855F7 | 0.14 |
| Accountability | checkmark.shield.fill | #EA580C | 0.11 |
| Forgiveness | drop.fill | #06B6D4 | 0.09 (most rare) |
4.2 Theme Synergies
When synergistic themes are played together: +8 power bonus
var synergyThemes: [Theme] {
switch self {
case .hope: return [.healing, .potential]
case .healing: return [.hope, .forgiveness]
case .confidence: return [.potential, .passion]
case .potential: return [.confidence, .hope]
case .passion: return [.freedom, .confidence]
case .freedom: return [.passion, .transcendence]
case .transcendence: return [.freedom, .time]
case .time: return [.transcendence, .accountability]
case .accountability: return [.time, .equality]
case .equality: return [.accountability, .forgiveness]
case .forgiveness: return [.equality, .healing]
case .fulfillment: return [.hope, .passion]
}
}4.3 Named Synergy Combinations
| Themes | Name |
|---|---|
| Hope + Healing | Recovery Boost |
| Confidence + Potential | Limitless Belief |
| Freedom + Transcendence | Boundless Spirit |
| Forgiveness + Healing | Inner Peace |
| Hope + Passion | Inspired Action |
| Time + Transcendence | Eternal Legacy |
| Accountability + Equality | Just Balance |
4.4 Theme Counters
When a counter theme is played: +10 power for counter, -8 for countered
var counterThemes: [Theme] {
switch self {
case .freedom: return [.accountability]
case .passion: return [.time]
case .accountability: return [.freedom]
case .time: return [.passion]
default: return []
}
}4.5 Theme Interaction Result
struct ThemeInteraction {
let theme1: Theme
let theme2: Theme
let isSynergy: Bool
let powerModifier: Int // +8 synergy, +10 counter, -8 countered
var bonusMultiplier: Double {
if isSynergy { return 1.5 }
if isCounter { return 0.5 }
return 1.0
}
}---
5. Ability Engine
### 5.1 Ability Execution Flow
File: `Services/AbilityEngine.swift`
Card Played
│
▼
Check Trigger Type
│
├── ON_PLAY → Execute immediately
├── PASSIVE → Always active
├── RESONANCE → Check theme match
├── REFLECTION → Check if question answered
└── ON_DISCARD → Execute when discarded
│
▼
Calculate Effect
│
▼
Return AbilityResult5.2 Ability Result
struct AbilityResult {
let ability: CardAbility
let wasTriggered: Bool
let effects: [EffectResult]
var totalGrowthGained: Int
var totalWisdomGained: Int
var cardsDrawn: Int
}
struct EffectResult {
let effectType: CardAbility.AbilityEffect
let description: String
var growthChange: Int?
var wisdomChange: Int?
var cardsDrawn: Int?
var bonusMultiplier: Double?
}5.3 Effect Values (from GameRules)
| Effect | Value |
|---|---|
| Reflection Growth Bonus | +20 |
| On-Play Growth Bonus | +15 |
| Resonance Growth Bonus | +10 |
| Passive Growth Bonus | +5 |
| Discard Growth Bonus | +8 |
| Healing Aura Growth | +5 |
| Healing Aura Wisdom | +1 |
| Resonance Multiplier | 1.5x |
| Theme Bonus per Match | +3 |
5.4 Synergy Calculation
func calculateThemeSynergy(
playerCard: Card,
opponentCard: Card,
playedPlayerThemes: [Theme]
) -> SynergyResult
struct SynergyResult {
let playerTheme: Theme
let opponentTheme: Theme
let type: SynergyType // synergy, counter, countered, neutral
let powerModifier: Int
let description: String
}---
6. Deck System
### 6.1 Deck Constraints
File: `Models/Deck.swift`
| Constraint | Value |
|---|---|
| Minimum cards | 20 |
| Maximum cards | 40 |
| Recommended size | 30 |
| Max themes | 3 primary |
| Max legendary copies | 1 per card |
| Max epic copies | 2 per card |
| Max rare copies | 2 per card |
| Max uncommon/common | 3 per card |
6.2 Deck Structure
struct Deck: Identifiable, Codable {
let id: String
var name: String
var cardIds: [String]
var primaryThemes: [Theme] // Max 3
let createdAt: Date
var lastModified: Date
var winCount: Int
var lossCount: Int
var isValid: Bool {
cardCount >= 20 && cardCount <= 40 && primaryThemes.count <= 3
}
}6.3 Deck Builder Helper
struct DeckBuilder {
var deck: Deck
var availableCards: [Card]
var themeDistribution: [Theme: Int]
var rarityDistribution: [Rarity: Int]
var averageWisdomCost: Double
var averagePower: Double
func suggestedCards(limit: Int = 5) -> [Card] // Synergy-based suggestions
func canAdd(_ card: Card) -> Bool // Rarity limit check
}---
7. Persistence Layer
### 7.1 SwiftData Models
File: `Models/PersistentModels.swift`
| Model | Purpose | Key Fields |
|---|---|---|
| OwnedCard | Player's collection | cardId, playCount, masteredAt, source |
| SavedDeck | Saved deck configurations | name, cardIds, primaryTheme, winCount |
| BattleRecord | Battle history | opponentName, playerWon, victoryType, ratingChange |
| UserProfile | Local settings & stats | nickname, rating, totalWins, settings |
| DailyWisdom | Cached daily card | date, cardId, text |
| PendingSyncAction | Offline action queue | actionType, payload |
### 7.2 Persistence Manager
File: `Services/PersistenceManager.swift`
@MainActor
class PersistenceManager: ObservableObject {
static let shared = PersistenceManager()
// Published state
@Published var userProfile: UserProfile?
@Published var ownedCards: [OwnedCard]
@Published var savedDecks: [SavedDeck]
@Published var battleHistory: [BattleRecord]
// Collection operations
func unlockCard(_ cardId: String, source: CardSource) -> OwnedCard?
func recordCardPlayed(_ cardId: String, won: Bool)
func setFavorite(_ cardId: String, rank: Int?)
// Deck operations
func createDeck(name: String, cardIds: [String], primaryTheme: Theme) -> SavedDeck
func updateDeck(_ deck: SavedDeck, name: String?, cardIds: [String]?)
func deleteDeck(_ deck: SavedDeck)
func setActiveDeck(_ deck: SavedDeck)
// Battle operations
func recordBattle(...) -> BattleRecord
// Statistics
var collectionStats: CollectionStats
var battleStats: BattleStats
}7.3 Card Mastery System
// Mastery requires: 10 plays + 5 wins
var isMastered: Bool {
playCount >= 10 && winCount >= 5
}
var masteryProgress: Double {
let playProgress = min(Double(playCount) / 10.0, 1.0)
let winProgress = min(Double(winCount) / 5.0, 1.0)
return (playProgress + winProgress) / 2.0
}---
8. Victory Conditions
8.1 Three Paths to Victory
| Victory Type | Requirement | Strategy |
|---|---|---|
| Enlightenment | 100 Emotional Growth points | High-power cards, theme synergies |
| Wisdom | Play all 12 themes | Diverse deck, theme coverage |
| Resonance | Trigger 5 perfect combos | Synergy pairs, combo stacking |
8.2 Victory Check Implementation
func checkVictory() -> (winner: String, condition: VictoryCondition)? {
// Check Enlightenment (100 growth)
if player.emotionalState.growthPoints >= 100 {
return (player.id, .enlightenment)
}
// Check Wisdom (all 12 themes)
if player.emotionalState.activeThemes.count >= 12 {
return (player.id, .wisdom)
}
// Check Resonance (5 combos)
if player.emotionalState.resonanceComboCount >= 5 {
return (player.id, .resonance)
}
return nil
}8.3 Growth Point Sources
| Source | Growth Points |
|---|---|
| Base card power | 10-100 (modified by type) |
| Theme synergy | +8 |
| Counter bonus | +10 |
| Reflection answer | +20 |
| On-play ability | +15 |
| Resonance ability | +10 |
| Passive ability | +5 |
| Theme harmony | +3 per matching theme |
---
9. AI Opponent System
### 9.1 AI Levels
File: `Models/Battle.swift`
| Level | Optimal Play |
|---|---|
| Novice | 30 |
| Apprentice | 50 |
| Sage | 80 |
| Enlightened | 95 |
9.2 AI Decision Framework (To Implement)
class AIOpponent {
let level: AILevel
func selectCardToPlay(hand: [Card], wisdom: Int, gameState: BattleState) -> Card? {
switch level {
case .novice:
return selectRandomPlayable(hand: hand, wisdom: wisdom)
case .apprentice:
return selectBestThemeMatch(hand: hand, wisdom: wisdom, gameState: gameState)
case .sage:
return selectOptimalPlay(hand: hand, wisdom: wisdom, gameState: gameState)
case .enlightened:
return selectAdaptivePlay(hand: hand, wisdom: wisdom, gameState: gameState)
}
}
}---
10. Game Rules Reference
### 10.1 Turn Structure Constants
File: `Models/GameRules.swift`
enum GameRules {
enum Battle {
static let startingHandSize = 5
static let maxHandSize = 10
static let cardsPerDraw = 1
static let turnTimeLimit: TimeInterval = 90
}
enum Wisdom {
static let startingPool = 3
static let maxCapacity = 5
static let regenPerTurn = 2
}
enum Victory {
static let enlightenmentThreshold = 100
static let wisdomThemeCount = 12
static let resonanceComboCount = 5
}
}10.2 Matchmaking
enum Matchmaking {
static let ratingRange = 200 // Initial ±200 ELO
static let maxWaitTime = 60 // Seconds before expanding
static let rangeExpansion = 100 // Expand by ±100 each timeout
}10.3 Progression
enum Progression {
static let masteryPlayCount = 10
static let ratingPerWin = 25
static let ratingPerLoss = -15
static let victoryConditionBonus = 10
}---
11. Component Dependency Graph
┌─────────────────┐
│ GameRules │ ◄── Source of truth for all constants
└────────┬────────┘
│
┌───────────────────┼───────────────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Theme │ ◄────►│ Card │ ◄────►│ Deck │
└────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │
│ ┌───────────┴───────────┐ │
│ │ │ │
▼ ▼ ▼ ▼
┌──────────────┐ ┌──────────────┐
│AbilityEngine │◄────────────►│ Battle │
└──────┬───────┘ └──────┬───────┘
│ │
│ ┌───────────────────┤
│ │ │
▼ ▼ ▼
┌──────────────────┐ ┌──────────────┐
│ BattleState │ │ User │
└────────┬─────────┘ └──────┬───────┘
│ │
└──────────┬───────────────┘
│
▼
┌─────────────────────┐
│ PersistenceManager │ ◄── Persists all game data
└─────────────────────┘---
12. Implementation Checklist
### Phase 1: Core Models (Foundation)
- [x] Card.swift - Card, CardType, Rarity, CardAbility
- [x] Theme.swift - Theme enum with synergies/counters
- [x] Deck.swift - Deck structure and validation
- [x] User.swift - User model with stats
- [x] GameRules.swift - All game constants
### Phase 2: Battle System (Engine)
- [x] Battle.swift - BattlePhase, BattleState, EmotionalState
- [x] AbilityEngine.swift - Ability execution
- [ ] BattleEngine.swift - Turn management, phase transitions
- [ ] BattleViewModel.swift - State management for UI
### Phase 3: Persistence (Data)
- [x] PersistentModels.swift - SwiftData models
- [x] PersistenceManager.swift - CRUD operations
- [ ] SyncManager.swift - Backend synchronization
### Phase 4: AI System
- [ ] AIOpponent.swift - AI decision making
- [ ] AIStrategy.swift - Level-specific strategies
### Phase 5: Multiplayer
- [ ] AblyManager.swift - Real-time communication
- [ ] MatchmakingService.swift - Player matching
- [ ] BattleNetworkManager.swift - Sync battle state
### Phase 6: UI Components
- [x] CardView.swift - Card rendering
- [x] PhysicalCardView.swift - Physical card assets
- [ ] BattleArenaView.swift - Battle UI (needs completion)
- [ ] DeckBuilderView.swift - Deck building (needs completion)
---
Quick Reference: Key Interfaces
Playing a Card
// 1. Check if can afford
guard emotionalState.spendWisdom(card.wisdomCost) else { return }
// 2. Execute abilities
let results = AbilityEngine.shared.executeOnPlayAbilities(
card: card,
playerThemes: activeThemes,
opponentCard: opponentCard,
reflectionAnswered: answeredQuestion
)
// 3. Calculate synergies
let synergy = AbilityEngine.shared.calculateThemeSynergy(
playerCard: card,
opponentCard: opponentCard,
playedPlayerThemes: Array(emotionalState.activeThemes)
)
// 4. Update state
emotionalState.activateTheme(card.primaryTheme)
emotionalState.addGrowth(totalGrowth)
// 5. Check victory
if let victory = checkVictory() { endBattle(victory) }Calculating Growth
let baseGrowth = card.effectivePower
let synergyBonus = synergy.powerModifier
let abilityBonus = results.reduce(0) { $0 + $1.totalGrowthGained }
let totalGrowth = baseGrowth + synergyBonus + abilityBonusCreating a Battle
let battle = Battle(
id: UUID().uuidString,
type: .ranked,
player1Id: user.id,
player2Id: opponent.id,
player1DeckId: activeDeck.id,
player2DeckId: opponentDeck.id,
state: initialState,
startedAt: Date()
)---
Notes for Development
1. All constants are in GameRules.swift - Never hardcode game values elsewhere
2. Theme interactions are bidirectional - Always check both directions
3. Abilities trigger in order - ON_PLAY → RESONANCE → REFLECTION → PASSIVE
4. Victory checks happen after Growth phase - Not during card play
5. Wisdom regenerates at turn start - Before draw phase
6. Persistence is async-safe - All SwiftData operations via PersistenceManager
---
Last Updated: December 2024
Version: 1.0.0
Promotion Decision
Promote into a technical note or architecture paper with implementation anchors.
Source Anchor
projects/Meaning-Full-Power/docs/GAME_MECHANICS_ARCHITECTURE.md
Detected Structure
Method · Evaluation · Code Anchors · Architecture