'use strict'; /** * ╔══════════════════════════════════════════════════════════════════════════╗ * AI Engine — v23.0 | محرك الذكاء الاصطناعي للبوتات ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ Decision Trees: قرارات ذكية بناءً على البيئة ║ * ✅ Environment Analysis: تحليل الكتل، الأعداء، الموارد، الإضاءة ║ * ✅ Player Learning: تعلم من سلوك اللاعبين الآخرين ║ * ✅ Adaptive Behavior: تكيّف مع الظروف المتغيرة ║ * ✅ Threat Assessment: تقييم التهديدات واتخاذ قرارات ║ * ✅ Goal System: أهداف قصيرة وطويلة المدى ║ * ✅ Memory System: تذكّر الأماكن والأحداث ║ * ✅ Social Learning: تعلم التفاعلات الاجتماعية ║ * ✅ Risk/Reward: توازن المخاطرة والمكافأة ║ * ✅ Emergent Behavior: سلوكيات تظهر من التعقيد ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */ const { EventEmitter } = require('events'); const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms))); const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a; const pick = arr => arr[Math.floor(Math.random() * arr.length)]; const chance = pct => Math.random() * 100 < pct; const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); const lerp = (a, b, t) => a + (b - a) * t; const dist = (a, b) => Math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2); const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19); // ════════════════════════════════════════════════════════════════════════════ // أنواع القرارات // ════════════════════════════════════════════════════════════════════════════ const DECISION = Object.freeze({ EXPLORE: 'EXPLORE', MINE: 'MINE', BUILD: 'BUILD', FARM: 'FARM', FIGHT: 'FIGHT', FLEE: 'FLEE', REST: 'REST', SOCIALIZE: 'SOCIALIZE', GATHER: 'GATHER', CRAFT: 'CRAFT', PATROL: 'PATROL', FOLLOW: 'FOLLOW', GUARD: 'GUARD', HEAL: 'HEAL', TRADE: 'TRADE', IDLE: 'IDLE', }); // ════════════════════════════════════════════════════════════════════════════ // Memory System — تذكّر الأماكن والأحداث // ════════════════════════════════════════════════════════════════════════════ class MemorySystem { constructor(maxSize = 500) { this.locations = new Map(); this.events = []; this.players = new Map(); this.threats = []; this.resources = new Map(); this.maxSize = maxSize; this._log('MEMORY', 'تم إنشاء نظام الذاكرة'); } _log(tag, msg) { console.log(`[${tsNow()}] [AI-MEM] ${tag} ${msg}`); } rememberLocation(pos, data) { const key = `${Math.round(pos.x)},${Math.round(pos.y)},${Math.round(pos.z)}`; this.locations.set(key, { ...data, pos: { x: pos.x, y: pos.y, z: pos.z }, lastSeen: Date.now() }); if (this.locations.size > this.maxSize) { const oldest = [...this.locations.entries()].sort((a, b) => a[1].lastSeen - b[1].lastSeen)[0]; if (oldest) this.locations.delete(oldest[0]); } } rememberEvent(type, data) { this.events.push({ type, data, time: Date.now() }); if (this.events.length > this.maxSize) this.events.shift(); } rememberPlayer(username, data) { const existing = this.players.get(username) || { interactions: 0, trades: 0, fights: 0, lastSeen: 0 }; this.players.set(username, { ...existing, ...data, lastSeen: Date.now() }); } rememberThreat(pos, type, severity) { this.threats.push({ pos, type, severity, time: Date.now() }); this.threats = this.threats.filter(t => Date.now() - t.time < 300000); } rememberResource(pos, type, count) { const key = `${type}_${Math.round(pos.x)},${Math.round(pos.z)}`; this.resources.set(key, { type, count, pos, lastSeen: Date.now() }); } getNearbyThreats(pos, radius = 32) { return this.threats.filter(t => { const d = Math.sqrt((t.pos.x-pos.x)**2 + (t.pos.z-pos.z)**2); return d < radius; }); } getKnownResources(type, radius = 64) { return [...this.resources.values()].filter(r => r.type === type); } getPlayerReputation(username) { const p = this.players.get(username); if (!p) return 0; return (p.trades * 2 + p.interactions) - (p.fights * 3); } getStatus() { return { locations: this.locations.size, events: this.events.length, players: this.players.size, threats: this.threats.length, resources: this.resources.size, }; } } // ════════════════════════════════════════════════════════════════════════════ // Environment Analysis — تحليل البيئة // ════════════════════════════════════════════════════════════════════════════ class EnvironmentAnalyzer { constructor(bot) { this.bot = bot; this._log('ENV', 'تم إنشاء محلل البيئة'); } _log(tag, msg) { console.log(`[${tsNow()}] [AI-ENV] ${tag} ${msg}`); } analyze() { if (!this.bot?.entity) return this._emptyAnalysis(); const pos = this.bot.entity.position; return { time: this._getTime(), light: this._getLightLevel(pos), nearbyBlocks: this._getNearbyBlocks(pos), nearbyEntities: this._getNearbyEntities(pos), dangers: this._getDangers(pos), resources: this._getResources(pos), terrain: this._getTerrain(pos), weather: this._getWeather(), players: this._getNearbyPlayers(pos), inventory: this._getInventorySummary(), health: this.bot.health || 0, food: this.bot.food || 0, position: { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z) }, }; } _emptyAnalysis() { return { time:'unknown',light:0,nearbyBlocks:[],nearbyEntities:[],dangers:[], resources:[],terrain:'unknown',weather:'clear',players:[],inventory:{}, health:0,food:0,position:{x:0,y:0,z:0} }; } _getTime() { const day = this.bot.time?.isDay; const age = this.bot.time?.age || 0; return day ? 'day' : 'night'; } _getLightLevel(pos) { try { const block = this.bot.blockAt(pos); return block ? block.light : 0; } catch(_) { return 0; } } _getNearbyBlocks(pos) { const blocks = []; try { const seen = new Set(); for (let dx = -4; dx <= 4; dx++) { for (let dy = -2; dy <= 4; dy++) { for (let dz = -4; dz <= 4; dz++) { const b = this.bot.blockAt(pos.offset(dx, dy, dz)); if (b && !seen.has(b.name)) { seen.add(b.name); blocks.push({ name: b.name, count: (blocks.find(x=>x.name===b.name)||{}).count||0+1, dx, dy, dz }); } } } } } catch(_) {} return blocks.slice(0, 30); } _getNearbyEntities(pos) { const entities = []; try { for (const [id, entity] of Object.entries(this.bot.entities || {})) { if (!entity || entity === this.bot.entity) continue; const d = entity.position ? entity.position.distanceTo(pos) : Infinity; if (d < 32) { entities.push({ id, type: entity.type, name: entity.name || entity.username || 'unknown', distance: Math.round(d), position: entity.position ? { x: Math.round(entity.position.x), y: Math.round(entity.position.y), z: Math.round(entity.position.z) } : null, }); } } } catch(_) {} return entities; } _getDangers(pos) { const dangers = []; try { for (const entity of Object.values(this.bot.entities || {})) { if (!entity || !entity.position) continue; const d = entity.position.distanceTo(pos); if (d < 16 && (entity.type === 'hostile' || entity.type === 'mob')) { dangers.push({ type: entity.name || 'unknown', distance: Math.round(d), severity: d < 4 ? 'critical' : d < 8 ? 'high' : 'medium', }); } } } catch(_) {} return dangers; } _getResources(pos) { const resources = []; try { for (let dx = -8; dx <= 8; dx++) { for (let dy = -4; dy <= 8; dy++) { for (let dz = -8; dz <= 8; dz++) { const b = this.bot.blockAt(pos.offset(dx, dy, dz)); if (!b) continue; const name = b.name; if (name.includes('ore') || name.includes('diamond') || name.includes('gold') || name.includes('iron') || name.includes('coal') || name.includes('lapis') || name.includes('redstone') || name.includes('emerald') || name.includes('netherite')) { resources.push({ name, distance: Math.round(Math.sqrt(dx*dx+dy*dy+dz*dz)) }); } } } } } catch(_) {} return resources.slice(0, 20); } _getTerrain(pos) { try { const block = this.bot.blockAt(pos); if (!block) return 'unknown'; const name = block.name; if (name.includes('water') || name.includes('lava')) return 'fluid'; if (name.includes('sand') || name.includes('gravel')) return 'loose'; if (name.includes('stone') || name.includes('deepslate')) return 'stone'; if (name.includes('dirt') || name.includes('grass')) return 'earth'; if (name.includes('netherrack')) return 'nether'; if (name.includes('end_stone')) return 'end'; return 'other'; } catch(_) { return 'unknown'; } } _getWeather() { try { return this.bot?.weather || 'clear'; } catch(_) { return 'clear'; } } _getNearbyPlayers(pos) { const players = []; try { for (const [name, player] of Object.entries(this.bot.players || {})) { if (name === this.bot.username) continue; if (player?.entity) { const d = player.entity.position.distanceTo(pos); if (d < 32) { players.push({ name, distance: Math.round(d), isOP: player.isOP }); } } } } catch(_) {} return players; } _getInventorySummary() { const summary = { total: 0, items: {} }; try { for (const item of this.bot.inventory.items()) { summary.total += item.count; summary.items[item.name] = (summary.items[item.name] || 0) + item.count; } } catch(_) {} return summary; } } // ════════════════════════════════════════════════════════════════════════════ // Goal System — نظام الأهداف // ════════════════════════════════════════════════════════════════════════════ class GoalSystem { constructor() { this.goals = []; this.completedGoals = []; this.maxGoals = 10; this._log('GOALS', 'تم إنشاء نظام الأهداف'); } _log(tag, msg) { console.log(`[${tsNow()}] [AI-GOAL] ${tag} ${msg}`); } addGoal(priority, type, data = {}) { if (this.goals.length >= this.maxGoals) return; const goal = { id: `goal_${Date.now()}_${rand(1000,9999)}`, priority, type, data, created: Date.now(), status: 'active', progress: 0, }; this.goals.push(goal); this.goals.sort((a, b) => b.priority - a.priority); this._log('🎯', `هدف جديد: ${type} (أولوية: ${priority})`); return goal; } completeGoal(goalId) { const idx = this.goals.findIndex(g => g.id === goalId); if (idx >= 0) { const goal = this.goals.splice(idx, 1)[0]; goal.status = 'completed'; goal.completedAt = Date.now(); this.completedGoals.push(goal); this._log('✅', `هدف مكتمل: ${goal.type}`); return goal; } return null; } getCurrentGoal() { return this.goals[0] || null; } updateProgress(goalId, progress) { const goal = this.goals.find(g => g.id === goalId); if (goal) { goal.progress = clamp(progress, 0, 100); if (goal.progress >= 100) this.completeGoal(goalId); } } getStatus() { return { active: this.goals.length, completed: this.completedGoals.length, current: this.getCurrentGoal(), goals: this.goals.map(g => ({ type: g.type, priority: g.priority, progress: g.progress })), }; } } // ════════════════════════════════════════════════════════════════════════════ // Threat Assessment — تقييم التهديدات // ════════════════════════════════════════════════════════════════════════════ class ThreatAssessor { constructor() { this.threatMap = new Map(); this._log('THREAT', 'تم إنشاء مقيّم التهديدات'); } _log(tag, msg) { console.log(`[${tsNow()}] [AI-THRT] ${tag} ${msg}`); } assess(analysis) { let totalThreat = 0; const threats = []; for (const danger of analysis.dangers) { const severity = { critical: 10, high: 6, medium: 3, low: 1 }[danger.severity] || 1; totalThreat += severity; threats.push({ ...danger, score: severity }); } if (analysis.health < 6) totalThreat += 8; else if (analysis.health < 12) totalThreat += 3; if (analysis.food < 6) totalThreat += 5; if (analysis.time === 'night') totalThreat += 2; return { level: totalThreat > 15 ? 'critical' : totalThreat > 8 ? 'high' : totalThreat > 3 ? 'medium' : 'low', score: totalThreat, threats, shouldFlee: totalThreat > 12, shouldHeal: analysis.health < 10, shouldEat: analysis.food < 14, shouldRest: analysis.time === 'night' && totalThreat < 5, }; } } // ════════════════════════════════════════════════════════════════════════════ // Social Learning — التعلم الاجتماعي // ════════════════════════════════════════════════════════════════════════════ class SocialLearner { constructor() { this.interactions = []; this.personalities = new Map(); this._log('SOCIAL', 'تم إنشاء المتعلم الاجتماعي'); } _log(tag, msg) { console.log(`[${tsNow()}] [AI-SOC] ${tag} ${msg}`); } observeInteraction(username, type, data) { this.interactions.push({ username, type, data, time: Date.now() }); if (this.interactions.length > 200) this.interactions.shift(); this._updatePersonality(username, type); } _updatePersonality(username, interactionType) { const p = this.personalities.get(username) || { friendliness: 50, aggression: 50, helpfulness: 50, trust: 50, }; switch (interactionType) { case 'help': p.friendliness += 5; p.helpfulness += 3; break; case 'hurt': p.aggression += 10; p.trust -= 10; break; case 'trade': p.friendliness += 3; p.trust += 2; break; case 'chat': p.friendliness += 1; break; case 'gift': p.friendliness += 8; p.trust += 5; p.helpfulness += 3; break; } p.friendliness = clamp(p.friendliness, 0, 100); p.aggression = clamp(p.aggression, 0, 100); p.helpfulness = clamp(p.helpfulness, 0, 100); p.trust = clamp(p.trust, 0, 100); this.personalities.set(username, p); } getPersonality(username) { return this.personalities.get(username) || { friendliness: 50, aggression: 50, helpfulness: 50, trust: 50 }; } shouldTrust(username) { const p = this.getPersonality(username); return p.trust > 40; } shouldHelp(username) { const p = this.getPersonality(username); return p.friendliness > 30 && p.helpfulness > 30; } getStatus() { return { interactions: this.interactions.length, knownPlayers: this.personalities.size, }; } } // ════════════════════════════════════════════════════════════════════════════ // AI Engine — المحرك الرئيسي // ════════════════════════════════════════════════════════════════════════════ class AIEngine extends EventEmitter { constructor(bot, config = {}) { super(); this.bot = bot; this.config = { intelligence: config.intelligence || 'normal', aggression: config.aggression || 'balanced', curiosity: config.curiosity || 60, caution: config.caution || 50, sociability: config.sociability || 60, ...config, }; this.memory = new MemorySystem(); this.analyzer = new EnvironmentAnalyzer(bot); this.goals = new GoalSystem(); this.threatAssessor = new ThreatAssessor(); this.socialLearner = new SocialLearner(); this.currentDecision = DECISION.IDLE; this.decisionHistory = []; this.lastAnalysis = null; this._active = false; this._decisionTimer = null; this._analyzeTimer = null; this._personality = this._generatePersonality(); this._log('ENGINE', `تم إنشاء AI Engine — ذكاء: ${this.config.intelligence}`); } _log(tag, msg) { console.log(`[${tsNow()}] [AI] ${tag} ${msg}`); } _generatePersonality() { return { intelligence: pick(['low', 'normal', 'high', 'genius']), aggression: pick(['pacifist', 'balanced', 'aggressive', 'berserker']), curiosity: rand(20, 90), caution: rand(20, 80), sociability: rand(20, 90), patience: rand(20, 90), greed: rand(10, 80), bravery: rand(20, 90), workEthic: rand(30, 95), }; } start() { if (this._active) return; this._active = true; this._log('🟢', 'بدء محرك الذكاء الاصطناعي'); this._analyzeTimer = setInterval(() => { if (!this._active) return; this._analyzeEnvironment(); }, 3000); this._decisionTimer = setInterval(() => { if (!this._active) return; this._makeDecision(); }, 5000); } stop() { this._active = false; if (this._decisionTimer) { clearInterval(this._decisionTimer); this._decisionTimer = null; } if (this._analyzeTimer) { clearInterval(this._analyzeTimer); this._analyzeTimer = null; } this._log('🔴', 'إيقاف محرك الذكاء الاصطناعي'); } _analyzeEnvironment() { try { this.lastAnalysis = this.analyzer.analyze(); const threats = this.threatAssessor.assess(this.lastAnalysis); this.lastAnalysis.threats = threats; const pos = this.bot.entity?.position; if (pos) { this.memory.rememberLocation(pos, { terrain: this.lastAnalysis.terrain, light: this.lastAnalysis.light, resources: this.lastAnalysis.resources.length, dangers: this.lastAnalysis.dangers.length, }); } this.emit('analysis', this.lastAnalysis); } catch(_) {} } _makeDecision() { if (!this.lastAnalysis) return; const a = this.lastAnalysis; const t = a.threats; const p = this._personality; let decision = DECISION.IDLE; let reason = ''; // 1. طوارئ الصحة if (t.shouldHeal) { decision = DECISION.HEAL; reason = `صحة منخفضة: ${a.health.toFixed(1)}`; } // 2. طوارئ الطعام else if (t.shouldEat) { decision = DECISION.REST; reason = `طعام منخفض: ${a.food}`; } // 3. تهديد عالي else if (t.shouldFlee && p.bravery < 60) { decision = DECISION.FLEE; reason = `تهديد عالي: ${t.score}`; } else if (t.shouldFlee && p.bravery >= 60) { decision = DECISION.FIGHT; reason = `مواجهة تهديد: ${t.score}`; } // 4. ليل آمن else if (t.shouldRest && p.caution > 40) { decision = DECISION.REST; reason = 'ليل آمن — وقت للراحة'; } // 5. أعداء قريبون else if (a.dangers.length > 0 && p.aggression === 'aggressive') { decision = DECISION.FIGHT; reason = 'عدو قريب — مواجهة'; } else if (a.dangers.length > 0) { decision = DECISION.FLEE; reason = 'عدو قريب — تجنب'; } // 6. موارد قريبة else if (a.resources.length > 0 && p.greed > 40) { decision = DECISION.GATHER; reason = `موارد: ${a.resources[0]?.name}`; } // 7. لاعبون nearby else if (a.players.length > 0 && p.sociability > 50 && chance(30)) { decision = DECISION.SOCIALIZE; reason = `لاعب قريب: ${a.players[0]?.name}`; } // 8. وقت العمل else if (p.workEthic > 50 && chance(40)) { const workDecisions = [DECISION.MINE, DECISION.BUILD, DECISION.FARM, DECISION.EXPLORE]; decision = pick(workDecisions); reason = 'وقت العمل'; } // 9. استكشاف else if (p.curiosity > 40 && chance(25)) { decision = DECISION.EXPLORE; reason = 'فضول — استكشاف'; } // 10. م patrol else if (p.bravery > 50 && chance(15)) { decision = DECISION.PATROL; reason = 'دورية أمنية'; } else { decision = DECISION.IDLE; reason = 'لا يوجد مهمة محددة'; } if (decision !== this.currentDecision) { this.decisionHistory.push({ from: this.currentDecision, to: decision, reason, time: Date.now() }); if (this.decisionHistory.length > 50) this.decisionHistory.shift(); this._log('🧠', `قرار: ${this.currentDecision} → ${decision} (${reason})`); } this.currentDecision = decision; this.emit('decision', decision, reason, a); } getStatus() { return { active: this._active, personality: this._personality, currentDecision: this.currentDecision, memory: this.memory.getStatus(), goals: this.goals.getStatus(), social: this.socialLearner.getStatus(), decisionHistory: this.decisionHistory.slice(-10), config: this.config, }; } destroy() { this.stop(); this.removeAllListeners(); } } module.exports = { AIEngine, MemorySystem, EnvironmentAnalyzer, GoalSystem, ThreatAssessor, SocialLearner, DECISION };