Spaces:
Configuration error

File size: 5,293 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
'use strict';
/**
 * Sleeping 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 BED_BLOCKS = [
  'white_bed','orange_bed','magenta_bed','light_blue_bed',
  'yellow_bed','lime_bed','pink_bed','gray_bed',
  'light_gray_bed','cyan_bed','purple_bed','blue_bed',
  'brown_bed','green_bed','red_bed','black_bed',
];

class SleepingSystem extends EventEmitter {
  constructor(bot, config = {}) {
    super();
    this.bot = bot;
    this.config = {
      nightCheckInterval: 5000,
      sleepHour: 13000,
      wakeHour: 1000,
      ...config,
    };
    this._active = false;
    this._timers = [];
    this._sleeping = false;
    this._slept = 0;
    this._lastSleep = null;
    this._log('INIT', 'نظام النوم جاهز');
  }

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

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

    this._addTimer(() => this._checkTime(), this.config.nightCheckInterval);
  }

  stop() {
    this._active = false;
    this._sleeping = 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);
  }

  // ═══ فحص الوقت ═══
  _checkTime() {
    if (!this.bot?.entity || this._sleeping) return;
    const time = this.bot.time?.age;
    if (time === undefined) return;

    const dayTime = time % 24000;
    const isNight = dayTime > this.config.sleepHour || dayTime < this.config.wakeHour;

    if (isNight && !this._sleeping) {
      this._log('🌙', 'الليل — يدور على سرير');
      this._trySleep();
    }
  }

  // ═══ محاولة النوم ═══
  async _trySleep() {
    if (this._sleeping || !this.bot?.entity) return;

    // دور على سرير قريب
    const bed = this._findBed();
    if (!bed) {
      this._log('⚠️', 'لا سرير متاح — ينام على الأرض');
      this._sleepOnGround();
      return;
    }

    try {
      // امشي للسرير
      await this._walkTo(bed.position);

      // نام
      await this.bot.sleep(bed);
      this._sleeping = true;
      this._slept++;
      this._lastSleep = Date.now();
      this._log('😴', `نام (إجمالي: ${this._slept})`);
      this.emit('sleeping');

      // استنى لحد ما الصبح
      await this._waitForMorning();
    } catch(e) {
      this._log('❌', `ما قدر ينام: ${e.message}`);
      this._sleepOnGround();
    }
  }

  // ═══ دور على سرير ═══
  _findBed() {
    if (!this.bot) return null;
    const bedBlock = this.bot.findBlock({
      matching: (block) => BED_BLOCKS.includes(block.name),
      maxDistance: 16,
      count: 1,
    });
    return bedBlock;
  }

  // ═══ نوم على الأرض ═══
  _sleepOnGround() {
    if (!this.bot?.entity) return;
    this._sleeping = true;
    this._slept++;
    this._lastSleep = Date.now();
    this._log('😴', 'نام على الأرض');
    this.emit('sleeping');

    // نام لمدة 7 ثواني (بديل للنوم الحقيقي)
    setTimeout(() => {
      this._sleeping = false;
      this._log('☀️', 'استيقظ');
      this.emit('wakeup');
    }, 7000);
  }

  // ═══ انتظار الصبح ═══
  async _waitForMorning() {
    while (this._active && this._sleeping && this.bot?.entity) {
      const time = this.bot.time?.age;
      if (time === undefined) break;
      const dayTime = time % 24000;
      if (dayTime >= this.config.wakeHour && dayTime < this.config.sleepHour) {
        this._sleeping = false;
        this._log('☀️', 'استيقظ');
        this.emit('wakeup');
        break;
      }
      await sleep(1000);
    }
  }

  // ═══ استيقظ ═══
  async wakeUp() {
    if (!this._sleeping || !this.bot) return;
    try {
      await this.bot.wakeUp();
      this._sleeping = false;
      this._log('☀️', 'استيقظ يدوياً');
      this.emit('wakeup');
    } catch(_) {}
  }

  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(300, 800));
    this.bot.setControlState('forward', false);
  }

  getStats() {
    return {
      slept: this._slept,
      lastSleep: this._lastSleep ? new Date(this._lastSleep).toISOString() : null,
      sleeping: this._sleeping,
      active: this._active,
    };
  }

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

module.exports = { SleepingSystem, BED_BLOCKS };