JavaScript and TypeScript course Β· Module 9: Design Patterns and Architecture
Final Project: Jurassic Park Management System
In this lesson8
Welcome to the Jurassic Park genetic laboratory! After a long journey through the world of JavaScript, it's time for the challenge that wraps up this module. Dr. Henry Wu, the park's chief geneticist, entrusts you with creating a comprehensive management system that will oversee all aspects of the park's operation - from monitoring dinosaurs to managing visitor safety.
Project goal
Your task is to create an advanced JavaScript application that integrates all the technologies you've learned into one cohesive system. This will be your magnum opus - proof that you've mastered the art of JavaScript programming.
Functional requirements of the system
1. Dinosaur management system
Your system must enable:
// Example dinosaur data structure
const dinosaurSpecies = {
id: 'trex-001',
name: 'Tyrannosaurus Rex',
species: 'T-Rex',
genome: {
dnaSequence: '4A7B...9F2E', // DNA sequence
modifications: ['enhanced-strength', 'reduced-aggression'],
purity: 0.92, // 92% original DNA
gapsFilled: ['amphibian-dna', 'bird-dna']
},
physicalTraits: {
height: 5.6, // meters
weight: 8500, // kg
length: 12.8, // meters
age: 4, // years
healthStatus: 'excellent'
},
behavior: {
aggressionLevel: 7, // 1-10
intelligence: 8,
socialBehavior: 'territorial',
huntingPattern: 'ambush-predator'
},
habitat: {
enclosureId: 'sector-7',
temperature: { min: 18, max: 28, current: 24 },
humidity: { min: 60, max: 80, current: 72 },
terrainType: 'forest-plains'
},
status: 'active' // active, sedated, medical-care, quarantine
};2. Security monitoring system
// Security system structure
const securitySystem = {
alerts: {
breach: false,
evacuation: false,
containmentFailure: false,
emergencyProtocol: false
},
sensors: [
{
id: 'fence-sensor-001',
type: 'perimeter',
location: 'sector-7-north',
status: 'operational',
lastReading: Date.now(),
voltage: 10000 // fence voltage in volts
},
{
id: 'motion-detector-034',
type: 'motion',
location: 'visitor-center',
status: 'operational',
sensitivity: 'high',
detectedMovement: false
}
],
accessControl: {
keyCards: new Map(), // Card ID -> access level
restrictedAreas: ['genetic-lab', 'control-room', 'medical-bay'],
emergencyOverride: false
}
};3. Visitor management system
// Visitor management system
class VisitorManagementSystem {
constructor() {
this.visitors = new Map();
this.tours = new Map();
this.emergencyContactList = [];
this.evacuationProcedures = [];
}
registerVisitor(visitorData) {
const visitor = {
id: this.generateVisitorId(),
personalData: {
name: visitorData.name,
age: visitorData.age,
emergencyContact: visitorData.emergencyContact,
medicalConditions: visitorData.medicalConditions || [],
insurancePolicy: visitorData.insurancePolicy
},
visit: {
arrivalTime: new Date(),
departureTime: null,
tourType: visitorData.tourType, // 'standard', 'vip', 'research'
groupId: visitorData.groupId,
currentLocation: 'entrance',
visitedAreas: ['entrance']
},
safety: {
waiverSigned: false,
briefingCompleted: false,
emergencyProtocolsExplained: false,
trackingDevice: null
}
};
this.visitors.set(visitor.id, visitor);
return visitor.id;
}
trackVisitorLocation(visitorId, newLocation) {
const visitor = this.visitors.get(visitorId);
if (visitor) {
visitor.visit.currentLocation = newLocation;
visitor.visit.visitedAreas.push(newLocation);
this.validateSafetyProtocols(visitor);
}
}
}4. Genetic laboratory system
// Genetic laboratory system
class GeneticLaboratory {
constructor() {
this.dnaLibrary = new Map();
this.activeExperiments = [];
this.incubators = [];
this.sequencingMachines = [];
}
analyzeDNA(sampleId, dnaSequence) {
const analysis = {
sampleId,
sequenceLength: dnaSequence.length,
gcContent: this.calculateGCContent(dnaSequence),
mutations: this.detectMutations(dnaSequence),
viability: this.assessViability(dnaSequence),
recommendedModifications: [],
timestamp: new Date()
};
return analysis;
}
createNewSpecimen(parentDNA, modifications = []) {
const baseGenome = this.reconstructGenome(parentDNA);
const modifiedGenome = this.applyModifications(baseGenome, modifications);
const specimen = {
id: this.generateSpecimenId(),
genome: modifiedGenome,
generation: this.getParentGeneration(parentDNA) + 1,
created: new Date(),
status: 'developing',
expectedHatchTime: this.calculateHatchTime(modifiedGenome),
parentSpecimens: [parentDNA.id]
};
return this.initiateIncubation(specimen);
}
}Technical requirements
1. Application architecture
Your application must use:
- Module Pattern or ES6 Modules for code organization
- Observer Pattern for communication between components
- Factory Pattern for creating dinosaur and visitor objects
- Singleton Pattern for critical systems (security, main database)
// Example of modular architecture
// modules/ParkCore.js
class ParkCore {
constructor() {
if (ParkCore.instance) {
return ParkCore.instance;
}
this.systems = {
security: new SecuritySystem(),
genetic: new GeneticLaboratory(),
visitors: new VisitorManagementSystem(),
dinosaurs: new DinosaurRegistry(),
weather: new WeatherMonitoring(),
power: new PowerGrid()
};
this.eventBus = new EventBus();
this.setupSystemCommunication();
ParkCore.instance = this;
}
setupSystemCommunication() {
// Communication between systems via event bus
this.eventBus.subscribe('security.breach', (data) => {
this.systems.visitors.initiateEvacuation(data.location);
this.systems.dinosaurs.activateContainmentProtocol();
});
this.eventBus.subscribe('dinosaur.escaped', (data) => {
this.systems.security.raiseAlert('containment-failure', data);
this.systems.visitors.redirectToSafeZones(data.dangerRadius);
});
}
}2. Data management
// Data management system with localStorage and IndexedDB
class DataManager {
constructor() {
this.localDB = new LocalDatabase('park-data');
this.cache = new Map();
this.syncQueue = [];
}
async saveDinosaurData(dinosaur) {
try {
// Save to cache
this.cache.set(dinosaur.id, dinosaur);
// Save to localStorage as backup
localStorage.setItem(`dino_${dinosaur.id}`, JSON.stringify(dinosaur));
// Save to IndexedDB for larger data
await this.localDB.store('dinosaurs', dinosaur);
// Add to synchronization queue with server
this.queueForSync('dinosaurs', dinosaur.id, 'update');
} catch (error) {
console.error('Error saving dinosaur data:', error);
throw new DataError('Failed to save dinosaur data');
}
}
async loadParkState() {
try {
const [dinosaurs, visitors, security] = await Promise.all([
this.localDB.getAll('dinosaurs'),
this.localDB.getAll('visitors'),
this.localDB.get('security', 'current-state')
]);
return {
dinosaurs: dinosaurs || [],
visitors: visitors || [],
security: security || this.getDefaultSecurityState()
};
} catch (error) {
console.error('Error loading park state:', error);
return this.getEmergencyFallbackState();
}
}
}3. User interface
Your system must include:
- Main dashboard with an overview of all systems
- Dinosaur panel with a list, details, and management capabilities
- Security monitor with alerts and system status
- Visitor panel with a list of active tours
- Genetic laboratory with DNA analysis tools
- Reporting system with charts and statistics
// User interface example
class ParkInterface {
constructor(parkCore) {
this.park = parkCore;
this.currentView = 'dashboard';
this.refreshInterval = null;
this.setupEventListeners();
}
render() {
const app = document.getElementById('park-app');
app.innerHTML = `
<header class="park-header">
<h1>Jurassic Park Management System</h1>
<div class="system-status">${this.renderSystemStatus()}</div>
</header>
<nav class="park-navigation">
${this.renderNavigation()}
</nav>
<main class="park-content">
${this.renderCurrentView()}
</main>
<aside class="alerts-panel">
${this.renderAlerts()}
</aside>
`;
this.bindEvents();
}
renderDinosaurPanel() {
const dinosaurs = this.park.systems.dinosaurs.getAll();
return `
<div class="dinosaur-panel">
<h2>Dinosaur Management</h2>
<div class="dinosaur-grid">
${dinosaurs.map(dino => `
<div class="dinosaur-card" data-id="${dino.id}">
<div class="dino-header">
<h3>${dino.name}</h3>
<span class="status ${dino.status}">${dino.status}</span>
</div>
<div class="dino-stats">
<div class="stat">
<label>Age:</label>
<span>${dino.physicalTraits.age} years</span>
</div>
<div class="stat">
<label>Health:</label>
<span>${dino.physicalTraits.healthStatus}</span>
</div>
<div class="stat">
<label>Location:</label>
<span>${dino.habitat.enclosureId}</span>
</div>
</div>
<div class="dino-actions">
<button data-action="feed">Feed</button>
<button data-action="checkup">Checkup</button>
<button data-action="relocate">Relocate</button>
</div>
</div>
`).join('')}
</div>
<button class="add-dinosaur-btn" data-action="add-dinosaur">
+ Add new dinosaur
</button>
</div>
`;
}
bindEvents() {
// One listener on the container (event delegation): in an onclick attribute "this" would be the button, not ParkInterface
document.getElementById('park-app').onclick = (event) => {
const button = event.target.closest('[data-action]');
if (!button) return;
const id = button.closest('.dinosaur-card')?.dataset.id;
const actions = {
feed: () => this.feedDinosaur(id),
checkup: () => this.medicateCheckup(id),
relocate: () => this.relocateDinosaur(id),
'add-dinosaur': () => this.showAddDinosaurForm()
};
actions[button.dataset.action]?.();
};
}
}4. Emergency situation handling
// Emergency response system
class EmergencyResponseSystem {
constructor(parkCore) {
this.park = parkCore;
this.emergencyLevel = 0; // 0-5, where 5 is the highest
this.activeProtocols = [];
this.evacuationRoutes = this.loadEvacuationRoutes();
}
handleEmergency(type, severity, location, additionalData = {}) {
const emergency = {
id: this.generateEmergencyId(),
type, // 'containment-breach', 'power-failure', 'weather-emergency', 'medical'
severity, // 1-5
location,
timestamp: new Date(),
status: 'active',
data: additionalData
};
// Automatic procedures depending on type and severity
switch (type) {
case 'containment-breach':
this.handleContainmentBreach(emergency);
break;
case 'power-failure':
this.handlePowerFailure(emergency);
break;
case 'weather-emergency':
this.handleWeatherEmergency(emergency);
break;
case 'medical':
this.handleMedicalEmergency(emergency);
break;
default:
this.handleGenericEmergency(emergency);
}
return emergency.id;
}
handleContainmentBreach(emergency) {
const { location, data } = emergency;
// 1. Immediate lockdown of affected sector
this.park.systems.security.lockdownSector(location);
// 2. Activate evacuation protocol for visitors in the danger zone
const dangerZone = this.calculateDangerZone(location, data.dinosaurType);
this.park.systems.visitors.evacuateZone(dangerZone);
// 3. Deploy response team
this.deployResponseTeam('containment', location, data);
// 4. Notify all systems
this.park.eventBus.publish('emergency.containment-breach', {
location,
dangerZone,
estimatedContainmentTime: this.estimateContainmentTime(data.dinosaurType)
});
// 5. Automatic safety protocols
this.activateEmergencyProtocol('Code Red - Containment Breach');
}
}Advanced features
1. Real-time simulation
// Time simulation and life cycle system
class TimeSimulation {
constructor() {
this.gameTime = new Date();
this.timeMultiplier = 1; // 1 = real time, 60 = 1 minute = 1 hour
this.isRunning = false;
this.events = [];
}
start() {
this.isRunning = true;
this.simulationLoop();
}
simulationLoop() {
if (!this.isRunning) return;
// Update simulation time
this.gameTime = new Date(this.gameTime.getTime() + (1000 * this.timeMultiplier));
// Check scheduled events
this.processScheduledEvents();
// Simulate natural processes
this.simulateNaturalProcesses();
// Next iteration in one second
setTimeout(() => this.simulationLoop(), 1000);
}
simulateNaturalProcesses() {
// Dinosaur aging
this.ageDinosaurs();
// Weather changes
this.updateWeather();
// Resource consumption (energy, food)
this.consumeResources();
// Natural dinosaur behaviors
this.simulateDinosaurBehavior();
}
}2. AI system for dinosaurs
// Dinosaur artificial intelligence
class DinosaurAI {
constructor(dinosaur) {
this.dinosaur = dinosaur;
this.currentState = 'idle';
this.needs = {
hunger: 50,
thirst: 30,
social: 70,
territory: 80,
reproduction: 20
};
this.decisionTree = this.buildDecisionTree();
}
makeDecision() {
const context = this.gatherEnvironmentalData();
const urgentNeed = this.findMostUrgentNeed();
const decision = this.decisionTree.evaluate(urgentNeed, context);
return this.executeDecision(decision);
}
buildDecisionTree() {
return {
evaluate: (need, context) => {
if (need === 'hunger' && this.needs.hunger > 80) {
return this.findFood(context);
}
if (need === 'social' && this.dinosaur.behavior.socialBehavior === 'pack') {
return this.seekPackMembers(context);
}
if (need === 'territory' && context.intruders.length > 0) {
return this.defendTerritory(context.intruders);
}
return { action: 'wander', target: this.chooseRandomLocation() };
}
};
}
}Evaluation criteria
Your project will be evaluated according to the following criteria:
1. Functionality (30%)
- All required systems work correctly
- Error handling and edge cases
- Intuitive user interface
- Application responsiveness
2. Code and architecture (25%)
- Readable, well-commented code
- Proper use of design patterns
- Modular application structure
- Following JavaScript best practices
3. Advanced features (20%)
- Real-time system implementation
- AI for dinosaurs
- Advanced data management
- Reporting and analytics system
4. Creativity and innovation (15%)
- Unique features and solutions
- Interactive UI/UX elements
- Interesting extensions of the dinosaur theme
- Implementation of additional systems
5. Testing and documentation (10%)
- Unit tests for key functions
- API and architecture documentation
- User manual
- Code comments
Bonus challenges (extra points)
1. Genetic system with real DNA logic
Implement a real DNA sequence analysis system with:
- Genetic mutation algorithms
- Cross-species DNA breeding system
- Predicting physical traits based on genotype
- Simulating trait inheritance across generations
2. Multiplayer and real-time communication
Add multi-user functionality:
- WebSocket for real-time communication
- Shared park management by multiple users
- Chat between park managers
- State synchronization between clients
3. Advanced API and integrations
Connect with external services:
- Real weather data
- User geolocation
- Payment system for tickets
- Calendar reservation integration
4. Machine Learning and prediction
Add machine learning elements:
- Predicting dinosaur behavior
- Optimizing feeding schedules
- Analyzing visitor patterns
- Predicting system failures
Getting started
Step 1: Planning
- Draw a system architecture diagram
- Define main modules and their responsibilities
- Plan the data structure
- Create a list of MVP (Minimum Viable Product) features
Step 2: Implementing MVP
- Create the basic application structure
- Implement core classes (ParkCore, DataManager)
- Add the basic user interface
- Connect modules via event bus
Step 3: Expanding functionality
- Add each system individually
- Test integration between systems
- Implement advanced features
- Optimize performance
Step 4: Finalization
- Add error handling
- Write tests
- Create documentation
- Conduct final testing
Technical tips
File structure
jurassic-park-system/
βββ index.html
βββ css/
β βββ main.css
β βββ dashboard.css
β βββ components.css
βββ js/
β βββ core/
β β βββ ParkCore.js
β β βββ EventBus.js
β β βββ DataManager.js
β βββ systems/
β β βββ SecuritySystem.js
β β βββ DinosaurRegistry.js
β β βββ VisitorManager.js
β β βββ GeneticLab.js
β βββ ui/
β β βββ Dashboard.js
β β βββ DinosaurPanel.js
β β βββ SecurityMonitor.js
β βββ utils/
β β βββ helpers.js
β β βββ validators.js
β βββ app.js
βββ data/
β βββ dinosaurs.json
β βββ species-data.json
β βββ default-config.json
βββ tests/
βββ core.test.js
βββ systems.test.js
βββ integration.test.jsExample application initialization
// app.js - main application file
document.addEventListener('DOMContentLoaded', async () => {
try {
// Initialize system
const park = new ParkCore();
await park.initialize();
// Load data
const dataManager = new DataManager();
const savedState = await dataManager.loadParkState();
if (savedState) {
await park.loadState(savedState);
} else {
await park.initializeDefaultState();
}
// Initialize interface
const ui = new ParkInterface(park);
ui.render();
// Start simulation
const simulation = new TimeSimulation(park);
simulation.start();
console.log('Jurassic Park Management System started successfully!');
} catch (error) {
console.error('System initialization error:', error);
showErrorPage('Failed to start the park management system');
}
});This is your big end-of-module challenge, young programmer! It's time to show what you have learned and create something truly exceptional. Dr. Wu and the entire genetic laboratory are counting on you!
Good luck building the future of Jurassic Park!
Code for this lesson: index.js
// Dinosaur AI System
// Exercise: Implement a needs and behavior system
class DinosaurAI {
constructor(name, species) {
this.name = name;
this.species = species;
this.needs = { hunger: 50, energy: 80, social: 60 };
this.behavior = "idle";
}
// Implement the methods:
// updateNeeds() - update needs (random changes)
// decideBehavior() - make a behavior decision based on needs
// getStatus() - return the dinosaur's status
updateNeeds() {
// Your code here
}
decideBehavior() {
// Your code here
}
getStatus() {
// Your code here
}
}
const rex = new DinosaurAI("Blue", "Velociraptor");
console.log("Dinosaur AI:", rex.name, "Status:", rex.behavior);Docs entries used in this lesson
Spotted a mistake in this lesson?