Package Exports
- rpg-event-generator
- rpg-event-generator/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (rpg-event-generator) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
RPG Event Generator
A powerful procedural event generation system for RPG games, capable of creating virtually infinite contextual events based on player state and game world.
โจ Features
- Infinite Event Generation: Creates unique, contextual events using custom Markov chains and procedural techniques
- Player-Aware: Events adapt to player stats, career, relationships, life stage, reputation, and social standing
- 14+ Dramatic Event Types: From court scandals and noble duels to ancient curses and bandit kings
- Immersive Storytelling: Each event features rich narratives with atmospheric descriptions and meaningful consequences
- Dynamic Effects: Context-aware rewards and consequences that scale with character development and power level
- Career Integration: Events specifically tailored to noble, merchant, warrior, and criminal careers
- Relationship Impact: Events that affect and are affected by your social connections and personal history
- Seasonal & Location Themes: Events adapt to time of year and geographical setting for added immersion
- Consequence Tracking: Events can have long-term effects on character development and reputation
- Personality-Driven Choices: Multiple meaningful choices that define your character's personality and path
- Quality Filtering: Built-in filters ensure only interesting, non-generic events are generated
- Modular Design: Easy to integrate into existing game systems
- Highly Configurable: Customize training data, templates, and generation parameters
๐ Quick Start
npm install rpg-event-generatorimport { RPGEventGenerator, generateRPGEvent } from 'rpg-event-generator';
// Quick single event
const event = generateRPGEvent({
age: 25,
gold: 500,
influence: 15,
career: 'merchant'
});
console.log(event.title); // "Golden Opportunity"
console.log(event.description); // Procedurally generated description
console.log(event.choices); // Array of choices with effects
// Advanced usage with custom generator
const generator = new RPGEventGenerator({
stateSize: 2,
trainingData: ['Your custom story fragments...']
});
// Generate multiple events
const events = generator.generateEvents({
age: 30,
gold: 1000,
influence: 25,
career: 'knight',
skills: { combat: 60, diplomacy: 40 }
}, 3);๐ Usage Examples
Basic Event Generation
const generator = new RPGEventGenerator();
// Generate a random event
const event = generator.generateEvent();
console.log(event);
// {
// id: "event_1704567890123_xyz789",
// title: "Perilous Bandit King's Challenge",
// description: "The infamous bandit king blocks your path, offering you a choice: join his band or face certain death. Your business interests are directly affected by this development. Choose wisely, for the wrong path leads to ruin.",
// narrative: "The infamous bandit king blocks your path, offering you a choice: join his band or face certain death.",
// choices: [
// {
// text: "Join the bandits",
// effect: { gold: 375, reputation: -23, combat_skill: 12 },
// consequence: "bandit"
// },
// {
// text: "Challenge him to single combat",
// effect: { reputation: 32, health: -18 },
// requirements: { combat_skill: 60 },
// consequence: "hero"
// },
// {
// text: "Bribe your way past",
// effect: { gold: -320, safe_passage: true },
// consequence: "diplomat"
// }
// ],
// type: "BANDIT_KING",
// consequence: null,
// urgency: "normal",
// theme: "adventure",
// context: { /* player context used */ }
// }Context-Aware Events
const playerContext = {
age: 35,
gold: 2500,
influence: 40,
reputation: 25,
career: 'noble',
skills: {
diplomacy: 70,
combat: 45,
intrigue: 30
},
relationships: [
{ name: 'Lord Harrington', type: 'ally', relationship: 60 },
{ name: 'Lady Beaumont', type: 'lover', relationship: 45 }
],
location: 'capital',
season: 'winter'
};
const event = generator.generateEvent(playerContext);
// Generates events like:
// - Diplomatic missions (high diplomacy skill)
// - Court intrigue opportunities (high influence)
// - Social events involving relationships
// - Winter-themed challengesCustom Training Data
const customTrainingData = [
'In the shadowed alleys of the ancient city',
'The dragon\'s roar echoes through the mountains',
'Elven merchants display their enchanted wares',
'A dwarven smith forges weapons of legend',
'The tavern is filled with adventurers and mercenaries',
'Ancient runes glow with mystical power',
'The forest whispers secrets to those who listen'
];
const generator = new RPGEventGenerator({
trainingData: customTrainingData
});๐ง API Reference
RPGEventGenerator Class
Constructor Options
const generator = new RPGEventGenerator({
stateSize: 2, // Markov chain state size (default: 2)
trainingData: [...] // Custom training data array (optional)
});Methods
generateEvent(playerContext)- Generate a single eventgenerateEvents(playerContext, count)- Generate multiple eventsaddTrainingData(data)- Add more training dataresetTrainingData(data)- Reset with new training data
Player Context Object
{
age: number, // Player age
gold: number, // Player wealth
influence: number, // Political/social influence
reputation: number, // Social reputation
career: string, // Player's career/job
skills: { // Skill levels object
combat: number,
diplomacy: number,
// ... other skills
},
relationships: [{ // Array of relationships
name: string,
type: string, // 'friend', 'lover', 'ally', etc.
relationship: number // Relationship strength (0-100)
}],
location: string, // Current location
season: string // Current season
}Event Object Structure
{
id: string, // Unique event identifier
title: string, // Dynamic, context-aware title
description: string, // Rich procedural description
narrative: string, // Core story premise
choices: [{ // Array of meaningful choices
text: string, // Choice text with contextual flavor
effect: { // Effects scaled by context
gold?: number, // Wealth changes
influence?: number, // Social/political power
reputation?: number, // Social standing
health?: number, // Physical well-being
stress?: number, // Mental strain
karma?: number, // Moral standing
// ... many more effects
},
consequence: string // Long-term character effect
}],
type: string, // Rich event category (COURT_SCANDAL, etc.)
consequence: string|null, // Applied consequence after choice
urgency: string, // 'normal', 'high', 'critical'
theme: string, // 'political', 'criminal', 'supernatural', etc.
context: object // Full context used for generation
}๐ฎ Integration Guide
React Native Game Integration
import React, { useState, useEffect } from 'react';
import { RPGEventGenerator } from 'rpg-event-generator';
function GameEventSystem({ playerStats }) {
const [currentEvent, setCurrentEvent] = useState(null);
const [generator] = useState(() => new RPGEventGenerator());
useEffect(() => {
// Generate event when time advances
const event = generator.generateEvent(playerStats);
setCurrentEvent(event);
}, [playerStats, generator]);
const handleChoice = (choiceIndex) => {
const choice = currentEvent.choices[choiceIndex];
// Apply effects to player stats
applyEffects(choice.effect);
setCurrentEvent(null); // Clear event
};
if (!currentEvent) return null;
return (
<EventDialog
event={currentEvent}
onChoice={handleChoice}
/>
);
}Redux Integration
// Action creators
export const generateEvent = (playerContext) => {
const generator = new RPGEventGenerator();
const event = generator.generateEvent(playerContext);
return {
type: 'GENERATE_EVENT',
payload: event
};
};
export const resolveEvent = (eventId, choiceIndex) => ({
type: 'RESOLVE_EVENT',
payload: { eventId, choiceIndex }
});
// Reducer
const eventReducer = (state = {}, action) => {
switch (action.type) {
case 'GENERATE_EVENT':
return { ...state, currentEvent: action.payload };
case 'RESOLVE_EVENT':
return { ...state, currentEvent: null };
default:
return state;
}
};๐งช Testing
npm testThe package includes comprehensive tests covering:
- Event generation with various contexts
- Effect resolution
- Markov chain text generation
- Template selection algorithms
๐ฏ Event Types
Court & Political (Variable probability)
- Court Scandal: Royal court intrigue with betrayal and scandal
- Noble Duel: Honor challenges and duels of reputation
- Market Crash: Economic disasters affecting trade and wealth
- Trade War: Merchant rivalries and economic warfare
Criminal Underworld (Variable probability)
- Thieves' Guild: Criminal organization recruitment and underworld dealings
- Blackmail Opportunity: Leverage compromising information for gain
- Bandit King Challenge: Highway robbery and outlaw confrontations
Supernatural & Mysterious (Variable probability)
- Ancient Curse: Cursed artifacts and supernatural afflictions
- Ghostly Visitation: Spirits seeking justice or redemption
- Lost Civilization: Archaeological discoveries and ancient treasures
Personal & Dramatic (Variable probability)
- Forbidden Love: Romance across social boundaries with scandal
- Family Secret: Hidden lineage and ancestral revelations
- Desertion Temptation: Military crises testing loyalty and courage
- Mercenary Contract: Dangerous employment with high rewards
Adventure & Exploration (Variable probability)
- Bandit King: Confrontations with notorious outlaws
- Lost Civilization: Exploration of ancient ruins and artifacts
Probabilities dynamically adjust based on player career, skills, reputation, wealth, and current life circumstances.
๐ How It Works
1. Context Analysis
The generator analyzes player stats to understand their current situation and capabilities.
2. Template Selection
Based on context, it selects an appropriate event template from 14+ rich narrative types (Court Scandal, Forbidden Love, Ancient Curse, etc.).
3. Procedural Description
Uses custom Markov chains trained on immersive RPG-themed text to generate unique, atmospheric descriptions.
4. Dynamic Choices
Creates contextually appropriate choices with effects that scale based on player stats, career, and relationships.
5. Effect Resolution
Converts effect ranges into specific numbers and applies sophisticated context multipliers based on character background.
๐จ Customization
Custom Event Templates
const customTemplates = {
QUEST: {
title: 'Epic Quest',
choices: [
{ text: 'Accept the quest', effect: { influence: [20, 40] } },
{ text: 'Decline politely', effect: {} }
]
}
};
// Extend the generator
class CustomRPGEventGenerator extends RPGEventGenerator {
constructor(options) {
super(options);
this.templates = { ...this.templates, ...customTemplates };
}
}Custom Effect Types
// Add custom effects
const event = generator.generateEvent(playerContext);
// Custom effect resolution
function resolveCustomEffects(choice, playerContext) {
const effects = resolveEffect(choice.effect, playerContext);
// Add custom logic
if (effects.experience) {
// Handle experience gain
}
if (effects.relationshipChange) {
// Update relationship values
}
return effects;
}๐ Performance
- Generation Speed: ~10-50ms per event
- Memory Usage: ~2-5MB for trained Markov generator
- Infinite Variety: Can generate millions of unique events
- Scalable: Works with any number of players/contexts
๐ค Contributing
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
๐ License
MIT License - see LICENSE file for details.
๐ Acknowledgments
- Uses Chance.js for random number generation
- Custom Markov chain implementation for procedural text generation
๐จ Thematic Training Sets
Choose from different genres and settings for your RPG events:
// Fantasy (default) - knights, magic, dragons
const fantasyGen = new RPGEventGenerator({ theme: 'fantasy' });
// Fantasy with Norse culture - vikings, runes, fjords
const norseGen = new RPGEventGenerator({
theme: 'fantasy',
culture: 'norse'
});
// Sci-fi - corporations, AI, space exploration
const sciFiGen = new RPGEventGenerator({ theme: 'sci-fi' });
// Cyberpunk sci-fi - neon lights, megacorps, hackers
const cyberpunkGen = new RPGEventGenerator({
theme: 'sci-fi',
culture: 'cyberpunk'
});
// Historical - medieval politics, exploration, warfare
const historicalGen = new RPGEventGenerator({ theme: 'historical' });
// Victorian historical - industrial revolution, social reform
const victorianGen = new RPGEventGenerator({
theme: 'historical',
culture: 'victorian'
});โ๏ธ Event Chains
Create multi-part story sequences where events trigger follow-ups:
const generator = new RPGEventGenerator();
// Start a bandit rising chain
const firstEvent = generator.startChain('BANDIT_RISING');
console.log(firstEvent.title); // "Treacherous Bandit Ambush"
// Advance chain based on player choice
const nextEvent = generator.advanceChain(firstEvent.chainId, 'bandit');
console.log(nextEvent.title); // "Perilous Bandit King's Challenge"
// Available chains: BANDIT_RISING, COURT_SCANDAL_CHAIN, CURSE_OF_THE_ARTIFACT, MERCHANT_EMPIREEvent chains create more engaging narratives with escalating consequences and multi-stage stories.
๐ง Modular Event System
Create and manage custom event templates, training data, and chains:
const generator = new RPGEventGenerator();
// Register custom event templates
const customTemplate = {
title: 'Mystic Vision',
narrative: 'You experience a vivid prophetic dream showing future events.',
choices: [
{ text: 'Seek out the prophecy', effect: { wisdom: 15, risk: 20 } },
{ text: 'Dismiss it as a dream', effect: { stress: -10 } }
]
};
generator.registerEventTemplate('MYSTIC_VISION', customTemplate);
// Add custom training data for better text generation
generator.addCustomTrainingData([
'The ancient prophecy foretells of great change',
'Mystic visions reveal hidden truths to the worthy',
'Dreams of the future guide the destinies of heroes'
], 'mystical');
// Create custom event chains
const visionChain = {
name: 'Prophetic Journey',
description: 'A chain of events triggered by mystic visions',
stages: [
{ day: 1, template: 'MYSTIC_VISION' },
{ day: 5, template: 'ANCIENT_RUINS' },
{ day: 10, template: 'FINAL_PROPHECY' }
]
};
generator.registerEventChain('PROPHECY_CHAIN', visionChain);
// Export/import custom content for sharing
const customContent = generator.exportCustomContent();
// Share with other developers or save for backup
const anotherGenerator = new RPGEventGenerator();
anotherGenerator.importCustomContent(customContent);Custom Content Management:
- Templates:
getCustomTemplates(),unregisterEventTemplate() - Training Data: Organized by categories for easy management
- Event Chains:
getCustomChains(),unregisterEventChain() - Export/Import: Full backup and sharing capabilities
โ๏ธ Dynamic Difficulty Scaling
Events automatically scale based on player power level:
// Weak character (easy difficulty)
const weakling = { gold: 50, influence: 10 };
const easyEvent = generator.generateEvent(weakling);
// Rewards: 50% higher, penalties: 30% lower
// Powerful character (hard difficulty)
const hero = { gold: 50000, influence: 500, skills: { combat: 100 } };
const hardEvent = generator.generateEvent(hero);
// Rewards: 20% lower, penalties: 30% higher
// Legendary character (legendary difficulty)
const god = { gold: 200000, influence: 1000, skills: { combat: 200 } };
const epicEvent = generator.generateEvent(god);
// Rewards: 40% lower, penalties: 60% higherDifficulty Tiers:
- Easy (Power 0-50): Beginner-friendly events
- Normal (Power 25-150): Balanced challenges
- Hard (Power 100-300): Demanding encounters
- Legendary (Power 250+): Epic, high-stakes events
โฐ Time-Based Events
Events evolve over time with seasonal changes and long-term story arcs:
const generator = new RPGEventGenerator();
// Advance game time
const timeEvents = generator.advanceTime(30); // Advance 30 days
console.log('Season:', generator.getCurrentTime().season); // May change
// Start evolving storylines
generator.startTimeBasedChain('POLITICAL_UPRISING');
// - Day 1: Whispers of dissent
// - Day 7: Public protests
// - Day 14: Open rebellion
// - Day 21: Revolutionary climax
// Generate time-aware events
const seasonalEvent = generator.generateTimeAwareEvent(playerContext);
// Events adapt to current season with appropriate themesAvailable Time-Based Chains:
POLITICAL_UPRISING: Rebellion that builds over weeksECONOMIC_COLLAPSE: Market crisis with escalating consequencesMYSTICAL_AWAKENING: Supernatural events that intensify over time
Seasonal Events:
- Spring: Romance, renewal, festivals
- Summer: Tournaments, celebrations, activity
- Autumn: Harvest, preparation, scarcity
- Winter: Solstice rituals, survival challenges, warmth-seeking
๐ฎ Game Integration
For real game integration, use these methods instead of timers:
const generator = new RPGEventGenerator();
// Each game day, advance time and check for events
function onNewGameDay() {
const dueEvents = generator.advanceGameDay();
// Process each due event in your game
dueEvents.forEach(event => {
if (event.type === 'time_based_chain') {
// Generate the actual event for your game
const chainData = generator.timeSystem.timeBasedEvents.get(event.chainId);
const gameEvent = generator.generateChainEvent(chainData);
// Add gameEvent to your game's event system
triggerInGameEvent(gameEvent);
} else if (event.type === 'seasonal_random') {
// Generate a seasonal event
const seasonalEvent = generator.generateTimeAwareEvent(playerContext);
triggerInGameEvent(seasonalEvent);
}
});
}
// Save/Load game state
function saveGame() {
const gameState = generator.getGameState();
// Save gameState to your game's save file
}
function loadGame(savedState) {
generator.loadGameState(savedState);
// Game is now restored with proper time/chain state
}
// Monitor active chains
const activeChains = generator.getActiveTimeChains();
// Shows all ongoing storylines with their progressKey Benefits:
- Persistent State: Chains survive game saves/loads
- Event-Driven: No timers, events trigger when you advance days
- Game-Controlled: You control when time passes
- Multiple Events: Handle multiple events per day
๐บ๏ธ Cultural Context
Add regional/cultural flavor within each theme:
Fantasy Cultures
norse: Vikings, runes, mead halls, thunder godsarabian: Sultans, djinn, bazaars, flying carpetsceltic: Druids, fairy mounds, stone circles, clan warfareasian: Imperial courts, samurai, dragon spirits, tea ceremonies
Sci-Fi Cultures
cyberpunk: Neon cities, megacorps, neural implants, hackersspace_opera: Galactic empires, Jedi knights, hyperspace, alien ambassadorspost_apocalyptic: Wastelands, mutants, vault dwellers, irradiated ruins
Historical Cultures
medieval: Knights, castles, feudal lords, alchemistsvictorian: Industrial revolution, social reformers, steam powerancient_roman: Gladiators, senators, aqueducts, barbarian hordes
Cultural variants blend with base theme data for authentic regional flavor!
๐งช Testing
This package includes comprehensive test coverage with 45+ automated tests ensuring reliability and quality:
npm testTest Coverage Includes:
- โ Core Generation - Event creation and validation
- โ Context Adaptation - Player stat responsiveness
- โ Thematic Systems - Theme and culture switching
- โ Event Chains - Multi-stage story progression
- โ Difficulty Scaling - Power-based event adjustment
- โ Time Systems - Seasonal and temporal mechanics
- โ Modular Features - Custom content registration
- โ Edge Cases - Error handling and validation
- โ Integration - Game state persistence
All features are thoroughly tested with both unit and integration tests for maximum reliability.
๐ฎ Future Enhancements
- Multi-language Support: Generate events in different languages
- Event Dependencies: Complex prerequisite systems
- Event Modifiers: Weather, season, and environmental effects
- Character Relationships: NPC interaction networks
- Event Editor: Visual template creation interface
Generate infinite adventures with RPG Event Generator! โ๏ธ๐โจ