Перейти к содержимому
Mineforgian

Cobblemon:Crzbrain

CRZbrain is a Kotlin-based Fabric mod for Minecraft/Cobblemon that gives Pokemon an AI-powered brain featuring reinforcement learning, sentiment analysis, cross-trainer knowledge sharing, and adaptive response generation to make Pokemon interaction

Загрузки
680
Подписчики
7
Обновлён
1 марта 2026 г.
Лицензия
MIT

Опубликован 6 февраля 2026 г.

CRZbrain is a server-side Cobblemon plugin (Fabric mod for Minecraft 1.21.1) that adds an intelligent AI personality system to Pokemon. Here's what it does:

  • Smart Responses: Each Pokemon can generate context-aware responses using an embedded AI engine (SmartResponseGenerator), reacting to battles, interactions, and trainer behavior with unique personality
  • Reinforcement Learning: Pokemon learn from experience over time — successful interactions are reinforced, failed ones are penalized, using policy gradient methods with adaptive learning rates and experience replay (ReinforcementLearning.kt)
  • Sentiment Analysis: The system understands player messages in both Italian and English, analyzing emotional valence, arousal, and dominance (3D VAD model) with negation detection (AdvancedPatternMining.kt)
  • Adaptive Learning: Pokemon track what works and what doesn't, balancing exploration of new behaviors vs exploitation of proven ones (AdaptiveLearning.kt)
  • External AI Integration: Can optionally learn from external AI providers like Claude, OpenAI, and Gemini to enrich response quality (ExternalAILearning.kt)
  • Global Knowledge Network: Pokemon share knowledge across trainers — if one trainer teaches something, other Pokemon can benefit through consensus-based knowledge transfer (GlobalKnowledgeNetwork.kt)
  • Behavior Prediction & Topic Modeling: The system mines patterns from interactions to predict player behavior and understand conversation topics (AdvancedPatternMining.kt)

In short: it makes Pokemon feel alive — they learn, adapt, remember, and grow smarter the more you interact with them.

Центр версий

12 версий
  • Релиз3.0 МБ
  • Релиз3.0 МБ
  • Релиз3.0 МБ
  • Релиз3.0 МБ
  • Релиз3.0 МБ
  • Релиз2.9 МБ
  • Релиз2.9 МБ
  • Релиз2.9 МБ
  • Релиз2.9 МБ
  • Релиз2.9 МБ
  • Релиз2.8 МБ
  • Релиз2.6 МБ

Ченджлог

2.1.0Релиз1.21.1 · 1 марта 2026 г.

v3.9 — Changelog

Critical Fixes

  • RL learning now actually works. A key mismatch between how the AI tracked responses and how it scored them meant the reinforcement learning system was effectively doing nothing since v3.8. Fixed — Pokemon now genuinely
    learn which responses work best over time.
  • Response variety massively increased. A probability bug was squaring all content gate chances (a 30% chance was really 9%, a 5% chance was 0.25%). Fixed across 48 gates — Pokemon now use their full range of personality expressions, comments, and reactions.
  • Evolution responses no longer get cut off. Evolution is now treated as a critical event that bypasses the response budget limiter.

AI Quality

  • Smarter learning integration. The system that scores how much learning data is available was penalizing Pokemon for having more knowledge sources. Fixed — Pokemon with richer learning history now give better responses.
  • Knowledge graduation no longer wipes Pokemon memory. When shared knowledge was promoted to the global pool, it was being deleted from individual Pokemon. Fixed — your Pokemon keep everything they've learned.
  • No more duplicate reward tracking. The RL engine was double-counting rewards, making the learning signal noisy and unreliable. Fixed.
  • Exploration/exploitation balance stabilized. Negative feedback was pushing Pokemon toward random responses twice as fast as positive feedback pulled them back. Now balanced — Pokemon recover smoothly after bad interactions.
  • Italian sarcasm detection fixed. Expressions like "siiii!" and "noooo!" (genuine Italian enthusiasm) were being flagged as sarcasm. Fixed — only actual sarcastic elongations trigger detection now.
  • External AI learning data no longer cross-contaminates. Usage stats from one lookup category were bleeding into others, skewing diversity penalties. Fixed.

Stability

  • Save system is more resilient. If an async save fails, the mod now correctly retries next cycle instead of silently skipping it.
  • Relationship cleanup uses exact matching. Prevents edge cases where resetting one Pokemon could affect another
2.1.0Релиз1.21.1 · 17 февраля 2026 г.

● v3.8 Changelog

  1. Commands.kt Full Bilingual (~112 strings)
  • All 22 command handler functions now support English via Lang.t()
  • Labels: Species, Level, Friendship, Weather, Ability, Types, Status
  • Relationship types: BEST FRIENDS, FRIENDS, ACQUAINTANCES, NEUTRAL, DISLIKE, RIVALS
  • Time of day: Morning, Day, Sunset, Night, Dawn
  • Weather: Storm, Rain, Clear
  • All help text, error messages, admin commands, friendship bonuses, battle sync, world context
  1. RL Action Key Fix (CRITICAL BUG)
  • trackAction() was storing literal string "response" as action key since v2.4
  • All policies had only 1 action entry → RL scoring in SRG used part.take(40).lowercase() as lookup key → never matched "response" → getActionSuccessProbability() always returned default 0.5f
  • The entire RL scoring boost was non-functional since inception
  • Fix: now stores finalResponse.take(40).lowercase() as action key, matching what scoring looks up
  1. RL-Driven Response Generation (NEW)
  • New generation path using chooseBestAction() to produce response parts from learned policies
  • Guards: 30+ episodes (no cold start), action 5-150 chars, not old "response" key, success probability > 60%, budget-gated at 15%
  • Tracked as "rl_response" feature source for feedback loop
  1. Context Quality Threshold Lowered
  • SRG threshold: 0.5f → 0.35f (0.5 was blocking learning context for new/young Pokemon)
  • LCI: added enhancementScale — at quality 0.35 → 30% enhancement strength, at 0.5+ → 100%
  • New Pokemon now benefit from learning data much earlier
  1. LanguageGrowth Catchphrase Getter
  • Added public getCatchphrase(pokemonId): String? method
  • Catchphrases were already used internally in enrichResponse() at 5% chance, but now accessible externally
  1. ExternalAI Diversity Penalty Fix
  • Old: sqrt(excess) * 0.03 subtracted — response used 100 times still had ~70% quality
  • New: ln(1 + excess) * 0.06 multiplicative — 10 excess: ×0.86, 50: ×0.76, 100: ×0.72, 500: ×0.63
  • Floor at 5% prevents total data loss
  1. TPS Optimizations
  • Cache TTL: CACHE_TTL_TICKS 10 → 40 (0.5s → 2s) — event-based invalidation handles fast updates, TTL is just a fallback
  • GlobalKN flatMap: flatMap { listOf() + list }.toSet() → mutableSetOf() + forEach { addAll } — eliminates intermediate List allocation
  • GlobalKN eviction: sorts lightweight Pair<String, Float> instead of full Map.Entry objects
2.1.0Релиз1.21.1 · 13 февраля 2026 г.

CRZbrain v3.7 — Bugfix + Thread Safety + Performance + AI Quality

Thread Safety & Memory Leaks (Batch 1)

TickOptimizationSystem.kt

  • Fix: Replaced global lastWorldEventTick / lastRelationshipTick counters with per-player ConcurrentHashMap<UUID, Long> — previously only the first player in the loop would trigger world events each cycle, causing uneven event distribution across players
  • Fix: Added cleanupPokemon(pokemonId) method to remove stale entries from pokemonDistanceTier map (was never cleaned, leaked ~1KB/Pokemon/hour)
  • Fix: Added cleanupPlayer(playerUuid) method to remove per-player tick counters and cache on disconnect

AdaptiveLearning.kt

  • Fix: Wrapped LRU eviction of trainerPatterns in synchronized block with double-check pattern — concurrent modification could corrupt the map during eviction
  • Fix: Added dead zone handling for success rates between 0.3–0.6 — previously no preference was recorded for ambiguous responses, now both liked/disliked decay toward zero
  • Fix: Changed context matching from exact equals(ignoreCase=true) to fuzzy word-overlap matching (≥50% overlap) — strategies learned for "battle_wild" now also apply to "battle_wild_grass"
  • Fix: Improved duplicate strategy detection key for more reliable dedup

IntelligenceEvolution.kt

  • Fix: Wrapped recentResults ArrayDeque access in synchronized(stats) block — ArrayDeque is not thread-safe, concurrent addLast/removeFirst could throw ConcurrentModificationException
  • Fix: Limited word association pairs to max 8 random samples for large word lists (was O(n×5) linkConcepts calls for every message) — also capped context associations to 3×3 entries

LearningContextIntegration.kt

  • Fix: Added @Volatile annotation to contextWeightsDirty flag — without it, the JVM could cache the value in a CPU register and the save thread would never see updates from chat threads

DeepUnderstanding.kt

  • Fix: Replaced single-entry LRU eviction with bulk 20% removal when playerCommunicationPatterns exceeds 200 entries — was removing 1 entry per call, causing O(n) overhead every call after cap
  • Fix: Capped context string in learnContextualMeanings to 100 characters — unbounded joinToString was producing very long map keys, wasting memory
  • New: Added saveData() / loadData() persistence for playerCommunicationPatterns and learnedMeanings to config/CRZbrain/learning/deep_understanding.json — previously all learned communication styles and word meanings were lost on server restart

CRZbrainMod.kt

  • Integration: Added DeepUnderstanding.loadData() call in SERVER_STARTED handler
  • Integration: Added DeepUnderstanding.saveData() call in SERVER_STOPPING handler
  • Fix: Added TickOptimizationSystem.cleanupPlayer() call on player disconnect alongside existing invalidateCache()

PokemonLifecycleManager.kt

  • Fix: Added TickOptimizationSystem.cleanupPokemon(pokemonId) call in cleanupRamOnlyData() to remove stale distance tier entries when Pokemon are released or removed

Performance (Batch 2)

ReinforcementLearning.kt

  • Fix: Replaced O(n log n) sortByDescending in replay buffer eviction with O(n) minimum priority scan — buffer was being fully sorted on every single add just to remove one lowest-priority entry

ExternalAILearning.kt

  • Fix: Removed unnecessary .copy() calls for event/emotion/topic maps in learnFromResponse() — was duplicating every LearnedResponse 5 times (one per index), now shares same object reference for nature/event/emotion/topic (species keeps copy due to different eviction lifecycle). ~60% memory reduction on learned responses
  • Fix: Changed overuse penalty from linear (count - threshold) * 0.05f to sublinear sqrt(count - threshold) * 0.03f — linear penalty was killing responses after ~20 uses, sqrt curve is much gentler (4 over → -0.06, 16 over → -0.12, 100 over → -0.3)
  • Fix: Capped feedbackScore at [-10, 10] and feedbackCount at 50 — previously accumulated without bound, causing responses with many feedbacks to dominate all quality calculations

AdvancedPatternMining.kt

  • Fix: Replaced message.hashCode().toString() document ID with AtomicLong counter + System.nanoTime() — 32-bit hashCode collisions caused different messages to overwrite each other's topic distributions
  • Fix: Capped initial topic keywords to 50 on creation (was unbounded from long messages)

GlobalKnowledgeNetwork.kt

  • Fix: Replaced hash-based strategy ID "${context.hashCode()}_${strategy.hashCode()}" with string concatenation "${context}__${strategy}" — hash collisions caused different strategies to merge
  • Fix: Skip trainer diversity penalty when totalTrainers < 3 — with 1-2 players, diversity ratio was artificially low (0.3-0.5), unfairly penalizing consensus scores
  • Fix: When global knowledge map is full, evict entry with lowest consensus score instead of silently rejecting new knowledge — previously new valid knowledge was dropped once cap was reached

AI Quality & Bug Fixes (Batch 3)

SmartResponseGenerator.kt

  • Fix: Removed dead playerMessage != null null check at line 671 — playerMessage is a non-null String parameter, check was always true (compiler warning)
  • Fix: Removed dead playerMessage != null null check at line 2266 — same issue, second occurrence. Both pre-existing compiler warnings are now resolved (0 warnings)
  • Fix: Consolidated double playerMessage.split() into single cached split, reused for both learnConcept and linkConcepts calls
  • Fix: Replaced java.time.LocalDateTime.now().hour fallback with constant 12 (noon) — game time ≠ system time, using real clock for unrecognized timeOfDay strings was producing wrong learning context
  • Fix: Added division-by-zero guard for maxHp in HP percentage calculation — maxHp == 0 (eggs, data glitches) produced Infinity which toInt() converted to Int.MAX_VALUE
  • Fix: Raised learning context quality threshold from > 0.3f to > 0.5f — low-confidence context was degrading response quality by applying unreliable enhancements

MoveAnimationSystem.kt

  • Fix: Added distance check startPos.squaredDistanceTo(endPos) < 0.01 before normalize() in playSignatureAnimation — when attacker and target are at the same position, normalizing a zero vector produces NaN components, causing particle positioning to fail silently

Files Modified (13)

  1. sensors/TickOptimizationSystem.kt
  2. ai/embedded/AdaptiveLearning.kt
  3. ai/embedded/IntelligenceEvolution.kt
  4. ai/learning/LearningContextIntegration.kt
  5. ai/embedded/DeepUnderstanding.kt
  6. CRZbrainMod.kt
  7. PokemonLifecycleManager.kt
  8. ai/learning/ReinforcementLearning.kt
  9. ai/learning/ExternalAILearning.kt
  10. ai/learning/AdvancedPatternMining.kt
  11. ai/learning/GlobalKnowledgeNetwork.kt
  12. ai/embedded/SmartResponseGenerator.kt
  13. combat/MoveAnimationSystem.kt

New Persistence File

  • config/CRZbrain/learning/deep_understanding.json — stores player communication patterns and per-Pokemon learned word meanings
2.1.0Релиз1.21.1 · 12 февраля 2026 г.

v3.6: Defense System Disabled + Per-Pokemon Tick Optimization

Part A — PokemonDefenseSystem Disabled

  1. Removed PokemonDefenseSystem.register() from CRZbrainMod — no more tick handler (entity search every 1s for ALL Pokemon) and no damage listener
  2. Removed all PDS calls from PokemonCommandSystem — executeProtect(), executeActiveDefense(), executeAggressiveMode(), executeGuardMode(), executeStandDown() no longer call PokemonDefenseSystem
  3. Simplified updateDefendingState() — removed findHostilesNearPlayer() entity search, now just follows player (teleport if distance > 5.0)
  4. Simplified updateProtectingState() — removed findHostilesNearPlayer() entity search, now just stays near player (teleport if distance > 3.0)
  5. Disabled defense commands in Commands.kt — setDefenseMode(), showDefenseStatus(), showAllDefenseStatus(), activatePvPMode() all return "Sistema difesa disabilitato (v3.6)"
  6. Removed PDS.resetPokemon() from PokemonLifecycleManager
  7. Removed unused imports — PokemonDefenseSystem import removed from CRZbrainMod, Commands, PokemonCommandSystem, PokemonLifecycleManager

Part B — TickOptimizationSystem (New Unified Tick Dispatcher)

  1. Created sensors/TickOptimizationSystem.kt — single ServerTickEvents.END_SERVER_TICK handler replaces 3 separate handlers
  2. Strategy 1 — Temporal Staggering: Pokemon split into 2 groups via uuid.hashCode() % 2, updated on alternating ticks (halves peak load per tick)
  3. Strategy 2 — Distance-Based LOD: Pokemon >16 blocks from trainer (squaredDistanceTo > 256) skip every other update cycle (recalculated every 20 ticks)
  4. Strategy 3 — Frequency Reduction: Combat states stay at 10-tick interval, non-combat states (FOLLOWING, EXPLORING, DEFENDING, PROTECTING) doubled to 20 ticks; WorldEventSystem interval doubled from 600 to 1200 ticks (30s → 60s)
  5. Strategy 4 — Intelligent Batching: getActivePokemon() cached per player with 10-tick TTL (was called ~28 times per cycle, now 1); single player iteration loop instead of 3 separate loops
  6. Removed tick handler from PokemonCommandSystem — exposed updateSinglePokemon() public method, removed lastUpdateTick and UPDATE_INTERVAL
  7. Removed tick handler from WorldEventSystem — renamed checkWorldEvents() to checkWorldEventsForPlayer() and made it public, removed lastCheckTick and CHECK_INTERVAL_TICKS
  8. Removed tick handler from PokemonRelationshipSystem — added tickForPlayer() public method, removed lastInteractionTick and INTERACTION_COOLDOWN_TICKS
  9. Cache invalidation hooks — TickOptimizationSystem.invalidateCache() called on POKEMON_SENT_POST and DISCONNECT events; cleanup() called on SERVER_STOPPING
  10. handleSpontaneousDialogue() uses cached Pokemon list instead of calling PokemonUtils.hasActivePokemon() directly
  11. Removed unused imports — ServerTickEvents removed from WorldEventSystem, PokemonRelationshipSystem; HostileEntity/AnimalEntity/PlayerEntity removed from PokemonCommandSystem
2.1.0Релиз1.21.1 · 12 февраля 2026 г.

v3.5: Knowledge Graduation + SRG Optimization + Auto-Pruning + File Consolidation

  1. SRG Lazy Evaluation (SmartResponseGenerator.kt)
  • Problem: 35+ subsystems were called BEFORE the probability gate check. With average gate ~9%, 91% of subsystem calls were wasted CPU.
  • Fix: Inverted all probability gates so Random.nextFloat() < probability is checked BEFORE calling the subsystem. If the random check fails, the subsystem is never called.
  • Replaced parts.add() with parts.addPart() that tracks a partsCollected counter.
  1. SRG Part Budget System (SmartResponseGenerator.kt)
  • Problem: 30-50 response parts were generated per response, but only 2-3 were used.
  • Fix: budgetGate(probability) lambda that enforces limits:
    • After 8 parts collected: skip any gate with probability < 15%
    • After 12 parts collected: skip ALL remaining gates
    • Priority gates (critical health, shiny, near death, evolution) bypass the budget entirely
  1. Auto-Pruning of Stale Data (LearningSystem.kt + ExternalAILearning.kt)
  • Problem: Learning data accumulated indefinitely, files grew without bound.
  • Fix: pruneStaleData() runs every 5 minutes and removes:
    • Associations with strength < 0.1
    • Behavior patterns with < 3 observations AND older than 30 days
    • Lessons with importance < 3 AND older than 60 days
    • Pokemon knowledge with confidence < 0.3 AND not reinforced in 30 days
    • Terminology with frequency == 1 AND older than 14 days
    • ExternalAI responses with effectiveQuality < 0.1
  • Backward compatible: pre-v3.5 data (createdAt == 0) is never pruned by age
  1. ExternalAI File Consolidation (ExternalAILearning.kt)
  • Problem: 11 separate JSON files for ExternalAI learning data.
  • Fix: Consolidated to 3 files:
    • learned_responses.json (byNature + byEvent + byEmotion + byTopic + bySpecies + speciesLastUsed)
    • learned_phrases.json (phrases + expressions + openers + closers + conversationPatterns)
    • stats.json (unchanged)
  • Backward compatible: loads old 11-file format if new format not found, migrates on next save, then deletes old files
  1. Knowledge Graduation System (LearningSystem.kt)
  • Problem: Each Pokemon learns independently from scratch. Data accumulated per-Pokemon without cross-pollination.
  • Fix: graduateKnowledge() runs every 5 minutes and promotes validated knowledge:
    • Vocabulary appearing in 3+ Pokemon → shared vocabulary
    • Associations in 3+ Pokemon with avg strength > 0.5 → shared associations
    • Behavior patterns with successRate > 0.75 and 10+ observations in 2+ Pokemon → shared patterns
    • Knowledge with confidence > 0.8 and 5+ reinforcements in 2+ Pokemon → shared knowledge
    • Battle strategies from Pokemon with 20+ battles → shared battle meta
  • Graduated entries are removed from per-Pokemon data (files shrink over time)
  • bootstrapNewPokemon(): Pokemon with < 10 vocabulary items automatically receive graduated knowledge as a starting base
  • Saved to graduated_knowledge.json

Files Modified ┌───────────────────────────┬────────────────────────────────────────────────────────────────────┐ │ File │ Changes │ ├───────────────────────────┼────────────────────────────────────────────────────────────────────┤ │ SmartResponseGenerator.kt │ Lazy evaluation (35+ gates inverted) + Part budget system │ ├───────────────────────────┼────────────────────────────────────────────────────────────────────┤ │ LearningSystem.kt │ Knowledge graduation + auto-pruning + createdAt fields + version 5 │ ├───────────────────────────┼────────────────────────────────────────────────────────────────────┤ │ ExternalAILearning.kt │ File consolidation (11→3) + pruning │ ├───────────────────────────┼────────────────────────────────────────────────────────────────────┤ │ CRZbrainMod.kt │ Periodic graduation/pruning trigger (every 6000 ticks) │ └───────────────────────────┴────────────────────────────────────────────────────────────────────┘ Impact

  • CPU: ~91% reduction in subsystem calls, max 12 parts instead of 30-50
  • Disk: Files auto-shrink via graduation + pruning, 11 files → 3 for ExternalAI
  • AI Quality: New Pokemon inherit validated cross-Pokemon knowledge instead of starting from zero
  • Build: BUILD SUCCESSFUL, only 2 pre-existing warnings (playerMessage != null)
2.1.0Релиз1.21.1 · 11 февраля 2026 г.

v3.4: Bug Fix + Dead Code Activation + Full Bilingual Completion

Group A: Critical Bug Fixes + Dead Code Activation (4 fixes)

  1. timeOfDay always returned null (SRG.kt) — context.timeOfDay contains strings like "morning"/"night", but the code called .toIntOrNull() which always returned null, defaulting to hour=12. AdaptiveLearning's temporal patterns (learning when players are active) were completely broken. Fixed with a when mapping strings to representative hours.
  2. adaptResponse() never called (SRG.kt) — AdaptiveLearning had a fully implemented function that categorizes responses and modifies unsuccessful ones based on learned preferences. It was never called from anywhere. Now inserted in SRG's post-processing pipeline.
  3. isPreferred()/isAvoided() never called (SRG.kt + AdaptiveLearning.kt) — These functions check what response styles a Pokemon has learned to prefer or avoid. The data was being collected but never used. Now integrated into prioritizeResponseParts scoring: avoided categories get -15, preferred get +10. Also made adaptResponse() write response-shape categories (enthusiastic_short, questioning, hesitant, verbose, brief, standard) so preferences accumulate by response shape.
  4. AdaptiveLearning bilingual gaps — predictNextTrainerAction() and generatePreferenceComment() were Italian-only. Wrapped with Lang.t().

Group B: Performance + Persistence + ExternalAI (5 fixes)

  1. Per-call Regex in LearningSystem — Emoji regex was created inside updatePlayerPersonalityProfile() on every message. Hoisted to object-level private val EMOJI_REGEX.
  2. GlobalKnowledgeNetwork non-atomic writes — All 6 data files used direct File.writeText(). A crash during write = data corruption. Added atomicWrite() helper using temp file + rename pattern.
  3. ExternalAILearning bilingual gaps — Added 12 English interjections to extractExpressions(), 5 English question starters to extractConversationPatterns(), and an English self-reference check in evaluateQuality().
  4. AIHandler removeAt(0) — Replaced O(n) while-loop with bulk subList(0, excess).clear().
  5. PokemonDefenseSystem removeAt(0) — Same fix for target memory trimming.

Group C: Bilingual IntelligenceEvolution + LCI (~143 strings)

  1. IntelligenceEvolution — 31 strings across inductive/abductive/predictive inference, philosophical/analytical/pattern/learning comments, knowledge enrichment, and association recall.
  2. LearningContextIntegration — 112 strings across behavior prediction, tone adaptation, player references, battle insights, strategy phrases, and 8 emotion-response generators (comfort, joy, calming, affection, reassurance, supportive, playful, serious).

Group D: Bilingual EmotionalMomentum + LanguageGrowth (~252 strings)

  1. EmotionalMomentum — 160 strings: all 11 moods (EXCITED, SAD, LOVING, SCARED, PROUD, TIRED, CURIOUS, AGGRESSIVE, HAPPY, LONELY, CONFUSED) with nature variants, plus modifyResponseByState() (happiness additions, yawn prefix, energy additions, curiosity additions, confidence word replacements, sigh prefix, stress truncation, affection suffix).
  2. LanguageGrowth — 92 strings: emotive expressions across 5 complexity levels × 4 emotions, personal expressions by 4 nature categories × 5 levels, catchphrases by 4 categories, vocabulary upgrades using Lang.tMap() for IT→fancy-IT / EN→fancy-EN replacements, and acquired word usage templates.

Group E: Bilingual LearningSystem (~200 strings)

  1. LearningSystem — 200 strings across 19 functions: battle insights, learned phrases, popular topic comments, player expression usage, player relation comments, event mentions, emotional atmosphere comments, personalized greetings (5 player types × natures), player style adaptation, activity time comments, topic-based responses, player vocabulary usage, previous interaction references, learned response generation (vocabulary/associations/lessons), battle-related comments, fully personalized responses, growth comments, battle predictions, and known player greetings.
2.1.0Релиз1.21.1 · 11 февраля 2026 г.

LearningSystem.kt has been modified

2.1.0Релиз1.21.1 · 10 февраля 2026 г.

● v3.2 Fixes - AI Quality + Performance + Persistence (~55 fixes across 17 files)

Critical: RL + Persistence (7 fixes)

  1. RL: Fixed REINFORCE score function - Was advantage * (1-probability), now (advantage / probability).coerceIn(-3, 3) - same fix in experience replay
  2. RL: EMA baseline - Was cumulative average (stale after thousands of episodes), now 0.99avg + 0.01reward
  3. RL: O(n) chooseBestAction - Was O(n²) recomputing totalWeight per action inside maxByOrNull
  4. RL: Thread-safe stats - totalUpdates/totalRewardsPositive/totalRewardsNegative changed to AtomicInteger; reset() now also clears replayBuffers
  5. AdaptiveLearning: Full persistence - Was completely lost on restart! Now saves/loads 6 JSON files in config/CRZbrain/adaptive/
  6. AdaptiveLearning: Fixed importStrategy - Floor was 0.225 (below failure threshold), now maxOf(rate * 0.3, 0.4). Also fixed equals vs contains for context matching, capped trainerPatterns at 200
  7. CRZbrainMod: Shutdown saves 4 missing systems - Added ExternalAILearning, EmotionalMomentum, LearningContextIntegration, AdaptiveLearning to shutdown. Added LearningSystem.forceSave() to periodic async saves

High: Bug Fixes (14 fixes)

  1. SRG: Atomic read-and-remove for feedback attribution - Was race condition where another thread could read null between get() and remove()
  2. SRG: English keywords added to all scoring/filtering - Was Italian-only, English-speaking players got random responses instead of contextual ones
  3. SRG: Fixed part.first() crash - Changed to firstOrNull()?.isUpperCase() == true. Added probability gates to shiny/seasonal/first-Pokemon responses
  4. SRG: Cross-Pokemon RL transfer - Filter was using contains (impossible match on context strings), fixed to startsWith
  5. ExternalAILearning: English keywords - Added EN keywords to detectTopic (10 categories) and detectEmotion (6 categories)
  6. ExternalAILearning: Atomic writes + multiple fixes - All 11 files now use temp+rename atomic writes. Fixed diversityScore Gson deserialization. Fixed extractOpener while-loop. Added read-time quality decay
  7. DeepUnderstanding: Fixed 4 broken Regex - Escaped :) :( >:) special characters. Elongation pattern now requires 2+ repeated chars
  8. DeepUnderstanding: Fixed detectEmotion double-call - Was computing emotion twice per message. Added caps: 500 words/Pokemon in learnedMeanings, 200 players in communicationPatterns
  9. IntelligenceEvolution: Fixed totalKnowledge - Wasn't decremented after knowledge eviction. Fixed learningSpeed cap at 3.0 using maxOf instead of overwrite
  10. IntelligenceEvolution: Word-boundary Regex - "male" and "no" were matching inside other Italian words. Skip English context keys in enrichment. Minimum 2-word overlap for deductive inference
  11. LCI: Thread-safe inner maps - Changed mutableMapOf() to ConcurrentHashMap() inside getOrPut calls. Fixed quality score normalization (divide by totalWeightUsed)
  12. LCI: Feedback detection - Now requires keyword AND sentiment agreement. Was false-positive on common Italian words like "sono", "pokemon"
  13. APM: Fixed substring matching - Sentiment markers used substring contains (false positives). Now split into single-word Set checks + explicit multi-word contains
  14. EmbeddedAIProvider: Moods actually work - EXCITED was a no-op, ANGRY destroyed ellipses, TIRED never triggered. All 4 maps changed to ConcurrentHashMap

Medium: Performance (14 fixes)

  1. APM: Eliminated ~200 allocations per call - All per-call maps, lists, sets, regex moved to object-level vals
  2. APM: Sentiment cache String key - Was using hashCode (collisions). Added caps: 100 topics, 200 actions. synchronizedList for inner lists. Atomic file writes
  3. LearningSystem: Removed sync I/O from markDirty - Was calling checkAutoSave() which could block main thread. Pre-compiled 17 regex
  4. SmartConversation: Pre-compiled 20+ regex - normalizeMessage was creating new Regex objects per call. Hoisted SPECIES_QUIRKS map to object level
  5. MoveAnimationSystem: Cached getNearbyPlayers - Was doing 16 entity searches per attack, now does 2 (query once, pass list to all sub-functions)
  6. PokemonDefenseSystem: Cached entity search - One search per player shared across all Pokemon. Replaced sortedWith().first() with minWithOrNull()
  7. MemorySystem: Bulk eviction - removeAt(0) in while loop replaced with subList(0, excess).clear() (single array shift)
  8. LanguageGrowth: Word-boundary replacement - upgradeVocabulary now uses Regex word boundaries to avoid replacing inside other words
  9. EmotionalMomentum: Fixed stale lastUpdate - Added timestamp update in applyEmotionalTransfer and applyBuildup (was never refreshed, states appeared inactive)
  10. IntelligenceEvolution: Sliding window learning rate - Was using lifetime cumulative average (never changed after early episodes). Now uses window of last 50 results
  11. AdaptiveLearning: Normalized activityPattern - Was accumulating 0.1 per call (grew unbounded). Now stores raw counts, normalizes at read-time. feedbackHistory changed to ArrayDeque for O(1) removeFirst
  12. CRZbrainMod: Fixed sender duplicate - allNearbyPlayers included the sender themselves. Added cleanup of lastChatLearnTime on player disconnect
  13. ExternalAILearning: Removed double loadData() - init block was calling loadData() which was also called at server start
  14. LCI: Debounced saveContextWeights - Added dirty flag, only saves when explicitly called instead of on every weight update

Комментарии

Загружаем…