File size: 8,298 Bytes
a08f3c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
'use strict';
/**
 * Combat System — نظام القتال الواقعية
 * يكشف الوحوش، يهاجمها، يحمي نفسه، يستخدم الأسلحة المناسبة
 */
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 chance = pct => Math.random() * 100 < pct;
const dist = (a, b) => a.distanceTo(b);

const HOSTILE_MOBS = new Set([
  'zombie','skeleton','spider','creeper','enderman','witch',
  'slime','phantom','drowned','husk','stray','cave_spider',
  'blaze','ghast','magma_cube','witherskeleton','piglin_brute',
  'vindicator','evoker','pillager','ravager','vex','warden',
  'breeze','bogged'
]);

const WEAPON_RANK = {
  'netherite_sword': 9, 'netherite_axe': 8,
  'diamond_sword': 8, 'diamond_axe': 7,
  'iron_sword': 6, 'iron_axe': 5,
  'stone_sword': 4, 'stone_axe': 3,
  'wooden_sword': 2, 'wooden_axe': 1,
  'bow': 7, 'crossbow': 6, 'trident': 8,
};

class CombatSystem extends EventEmitter {
  constructor(bot, config = {}) {
    super();
    this.bot = bot;
    this.config = {
      aggroRange: 16,
      fleeHealthPct: 0.25,
      attackCooldown: 350,
      shieldSlot: 'off-hand',
      ...config,
    };
    this._active = false;
    this._timers = [];
    this._fighting = false;
    this._lastAttack = 0;
    this._kills = 0;
    this._damageTaken = 0;
    this._log('INIT', 'Combat system جاهز');
  }

  _log(tag, msg) {
    const ts = new Date().toISOString().replace('T', ' ').slice(0, 19);
    console.log(`[${ts}] [COMBAT] ${tag}  ${msg}`);
  }

  start() {
    if (this._active) return;
    this._active = true;
    this._log('START', 'بدء نظام القتال');

    // كشف الوحوش القريبة كل 2 ثانية
    this._addTimer(() => this._scanForHostiles(), 2000);

    // مراقبة الصحة كل ثانية
    this._addTimer(() => this._checkHealth(), 1000);

    // سلوك ليلي أكثر عدائية
    this._addTimer(() => this._nightBehavior(), 5000);
  }

  stop() {
    this._active = false;
    this._timers.forEach(t => { try { clearInterval(t); clearTimeout(t); } catch(_) {} });
    this._timers = [];
    this._fighting = false;
    this._log('STOP', 'إيقاف نظام القتال');
  }

  _addTimer(fn, interval) {
    const t = setInterval(() => { if (this._active) fn(); }, interval);
    this._timers.push(t);
    return t;
  }

  // ═══ كشف الوحوش القريبة ═══
  _scanForHostiles() {
    if (!this.bot?.entity || this._fighting) return;
    const pos = this.bot.entity.position;
    const hostiles = this.bot.entitiesArray.filter(e => {
      if (!e || e.type !== 'mob' || !e.name) return false;
      if (!HOSTILE_MOBS.has(e.name)) return false;
      if (!e.position) return false;
      return dist(pos, e.position) < this.config.aggroRange;
    });

    if (hostiles.length > 0) {
      const closest = hostiles.sort((a, b) => dist(pos, a.position) - dist(pos, b.position))[0];
      this._engage(closest);
    }
  }

  // ═══ مهاجمة مخلوق معين ═══
  async _engage(target) {
    if (this._fighting || !this.bot?.entity) return;
    this._fighting = true;
    this._log('⚔️', `هجوم على ${target.name}`);

    try {
      // اختر أفضل سلاح متاح
      await this._equipBestWeapon();

      // حط الدرع لو موجود
      await this._equipShield();

      // هاجم لحد ما يموت أو تقل صحتنا
      while (this._active && this.bot?.entity && target && target.health > 0) {
        if (!this.bot?.entity) break;

        // لو صحتنا قليلة، اهرب
        const health = this.bot.health;
        if (health && health < 6) {
          this._log('🏃', 'صحة قليلة — هروب!');
          await this._flee();
          break;
        }

        // ا approached للهدف
        const d = dist(this.bot.entity.position, target.position);
        if (d > 3.5) {
          await this._walkTo(target.position);
        }

        // اضرب
        if (Date.now() - this._lastAttack > this.config.attackCooldown) {
          try {
            await this.bot.attack(target);
            this._lastAttack = Date.now();
          } catch(_) {}
        }

        // حركات جانبية عشان يتجنب الهجمات
        if (chance(30)) {
          this._strafe();
        }

        await sleep(rand(100, 300));
      }

      if (target.health <= 0 || !target.entity) {
        this._kills++;
        this._log('💀', `قتل ${target.name} (إجمالي: ${this._kills})`);
        this.emit('kill', target.name);
      }
    } catch(e) {
      this._log('❌', `خطأ في القتال: ${e.message}`);
    } finally {
      this._fighting = false;
    }
  }

  // ═══ اختيار أفضل سلاح ═══
  async _equipBestWeapon() {
    if (!this.bot) return;
    const items = this.bot.inventory.items();
    let bestWeapon = null;
    let bestRank = -1;

    for (const item of items) {
      const rank = WEAPON_RANK[item.name] || 0;
      if (rank > bestRank) {
        bestRank = rank;
        bestWeapon = item;
      }
    }

    if (bestWeapon) {
      try {
        await this.bot.equip(bestWeapon, 'hand');
      } catch(_) {}
    }
  }

  // ═══ وضع الدرع ═══
  async _equipShield() {
    if (!this.bot) return;
    const shield = this.bot.inventory.items().find(i => i.name === 'shield');
    if (shield) {
      try {
        await this.bot.equip(shield, 'off-hand');
      } catch(_) {}
    }
  }

  // ═══ حركة هروب ═══
  async _flee() {
    if (!this.bot?.entity) return;
    const yaw = Math.random() * Math.PI * 2;
    this.bot.look(yaw, 0, false);
    this.bot.setControlState('forward', true);
    this.bot.setControlState('sprint', true);
    await sleep(rand(1500, 3000));
    this.bot.setControlState('forward', false);
    this.bot.setControlState('sprint', false);
  }

  // ═══ حركة جانبية ═══
  _strafe() {
    if (!this.bot?.entity) return;
    const dir = chance(50) ? 'left' : 'right';
    this.bot.setControlState(dir, true);
    setTimeout(() => { try { this.bot.setControlState(dir, false); } catch(_) {} }, rand(200, 500));
  }

  // ═══ المشي لهدف ═══
  async _walkTo(position) {
    if (!this.bot?.entity) return;
    const yaw = Math.atan2(
      position.z - this.bot.entity.position.z,
      position.x - this.bot.entity.position.x
    );
    this.bot.look(yaw, 0, false);
    this.bot.setControlState('forward', true);
    await sleep(rand(200, 500));
    this.bot.setControlState('forward', false);
  }

  // ═══ مراقبة الصحة ═══
  _checkHealth() {
    if (!this.bot?.entity) return;
    const health = this.bot.health;
    if (health !== undefined && health < 4) {
      // أكل طعام لو متاح
      this._eatIfAvailable();
    }
  }

  // ═══ أكل لو متاح ═══
  async _eatIfAvailable() {
    if (!this.bot) return;
    const food = this.bot.inventory.items().find(i =>
      i.name.includes('bread') || i.name.includes('cooked') ||
      i.name.includes('apple') || i.name.includes('steak') ||
      i.name.includes('porkchop') || i.name.includes('chicken')
    );
    if (food) {
      try {
        await this.bot.equip(food, 'hand');
        await this.bot.consume();
        this._log('🍖', 'أكل عشان يسترد الصحة');
      } catch(_) {}
    }
  }

  // ═══ سلوك ليلي ═══
  _nightBehavior() {
    if (!this.bot?.entity) return;
    const time = this.bot.time?.age;
    if (time === undefined) return;

    // الليل: أكثر عدائية، يدور على الوحوش
    const isNight = (time % 24000) > 12500 && (time % 24000) < 23000;
    if (isNight) {
      this.config.aggroRange = 24; // يشوف أبعد بالليل
    } else {
      this.config.aggroRange = 16;
    }
  }

  getStats() {
    return {
      kills: this._kills,
      damageTaken: this._damageTaken,
      fighting: this._fighting,
      active: this._active,
    };
  }

  destroy() {
    this.stop();
    this.removeAllListeners();
  }
}

module.exports = { CombatSystem, HOSTILE_MOBS };