Spaces:
Configuration error

File size: 6,309 Bytes
5871ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use strict';
/**
 * Farming 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 CROP_SEEDS = [
  'wheat_seeds','beetroot_seeds','melon_seeds','pumpkin_seeds',
];

const CROP_ITEMS = [
  'wheat','beetroot','melon_slice','pumpkin',
  'carrot','potato','nether_wart',
];

class FarmingSystem extends EventEmitter {
  constructor(bot, config = {}) {
    super();
    this.bot = bot;
    this.config = {
      farmRadius: 8,
      harvestInterval: 30000,
      ...config,
    };
    this._active = false;
    this._timers = [];
    this._farming = false;
    this._cropsPlanted = 0;
    this._cropsHarvested = 0;
    this._waterPlaced = false;
    this._log('INIT', 'نظام الزراعة جاهز');
  }

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

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

    this._addTimer(() => this._autoFarm(), this.config.harvestInterval);
  }

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

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

  // ═══ زراعة تلقائية ═══
  async _autoFarm() {
    if (this._farming || !this.bot?.entity) return;
    if (chance(40)) return;

    this._farming = true;
    try {
      // دور على أرض مزروعة قريبة
      const farmLand = this._findFarmLand();
      if (farmLand) {
        await this._harvestCrops(farmLand);
        await this._plantCrops(farmLand);
      } else {
        // ابني مزرعة جديدة
        await this._buildFarm();
      }
    } catch(e) {
      this._log('❌', `خطأ: ${e.message}`);
    } finally {
      this._farming = false;
    }
  }

  // ═══ دور على أرض مزروعة ═══
  _findFarmLand() {
    if (!this.bot?.entity) return null;
    const pos = this.bot.entity.position;
    for (let x = -this.config.farmRadius; x <= this.config.farmRadius; x++) {
      for (let z = -this.config.farmRadius; z <= this.config.farmRadius; z++) {
        const block = this.bot.blockAt(pos.offset(x, -1, z));
        if (block && block.name === 'farmland') {
          return block;
        }
      }
    }
    return null;
  }

  // ═══ حصد المحاصيل ═══
  async _harvestCrops(farmLand) {
    if (!this.bot?.entity) return;
    const pos = farmLand.position;

    for (let x = -2; x <= 2; x++) {
      for (let z = -2; z <= 2; z++) {
        const crop = this.bot.blockAt(pos.offset(x, 1, z));
        if (!crop) continue;

        // فحص لو المحصول ناضج (الكتلة فيها wheat بارتفاع 7)
        if (crop.name === 'wheat' || crop.name === 'beetroots' ||
            crop.name === 'carrots' || crop.name === 'potatoes') {
          if (crop.metadata >= 7 || crop.stateId) {
            try {
              await this.bot.dig(crop);
              this._cropsHarvested++;
              await sleep(rand(50, 150));
            } catch(_) {}
          }
        }
      }
    }
  }

  // ═══ زراعة بذور ═══
  async _plantCrops(farmLand) {
    if (!this.bot?.entity) return;
    const pos = farmLand.position;

    // دور على بذور في المخزون
    const seeds = this.bot.inventory.items().find(i =>
      CROP_SEEDS.includes(i.name) || i.name === 'carrot' || i.name === 'potato'
    );
    if (!seeds) return;

    try {
      await this.bot.equip(seeds, 'hand');
      for (let x = -2; x <= 2; x++) {
        for (let z = -2; z <= 2; z++) {
          if (!this.bot?.entity) break;
          const block = this.bot.blockAt(pos.offset(x, -1, z));
          const above = this.bot.blockAt(pos.offset(x, 0, z));
          if (block?.name === 'farmland' && above?.name === 'air') {
            try {
              await this.bot.placeBlock(block, { x: 0, y: 1, z: 0 });
              this._cropsPlanted++;
              await sleep(rand(50, 100));
            } catch(_) {}
          }
        }
      }
    } catch(_) {}
  }

  // ═══ بناء مزرعة جديدة ═══
  async _buildFarm() {
    if (!this.bot?.entity) return;
    const hoe = this.bot.inventory.items().find(i => i.name.includes('hoe'));
    if (!hoe) return;

    await this.bot.equip(hoe, 'hand');
    const pos = this.bot.entity.position;
    const base = { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z) };

    // حرث الأرض 5x5
    for (let x = -2; x <= 2; x++) {
      for (let z = -2; z <= 2; z++) {
        if (!this.bot?.entity) break;
        const block = this.bot.blockAt({ x: base.x + x, y: base.y - 1, z: base.z + z });
        if (block && (block.name === 'grass_block' || block.name === 'dirt')) {
          try {
            await this.bot.activateBlock(block);
            await sleep(rand(100, 200));
          } catch(_) {}
        }
      }
    }

    // ضع ماء في النص
    const water = this.bot.inventory.items().find(i => i.name === 'water_bucket');
    if (water) {
      try {
        await this.bot.equip(water, 'hand');
        const center = this.bot.blockAt({ x: base.x, y: base.y - 1, z: base.z });
        if (center) {
          await this.bot.placeBlock(center, { x: 0, y: 0, z: 0 });
          this._waterPlaced = true;
        }
      } catch(_) {}
    }

    this._log('🌾', 'بنى مزرعة جديدة');
    this.emit('builtFarm');
  }

  getStats() {
    return {
      cropsPlanted: this._cropsPlanted,
      cropsHarvested: this._cropsHarvested,
      farming: this._farming,
      active: this._active,
    };
  }

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

module.exports = { FarmingSystem, CROP_SEEDS, CROP_ITEMS };