View difference between Paste ID: BFNQGJ7f and XVVaPbYL
SHOW: | | - or go back to the newest paste.
1-
--pastebin get -f XVVaPbYL mag.lua && start.lua
1+
--pastebin get -f BFNQGJ7f mag.lua 
2
local un = require('unicode')
3
local c = require("component")
4
local pull_e = require('event').pull
5
local com = require("computer")
6
local fs = require("filesystem")
7
local term = require('term') 
8
local gpu = c.gpu
9
local me = c.me_interface
10
local W, H = gpu.getResolution()
11
local b_color, f_color = gpu.getBackground(), gpu.getForeground()
12
local tr = 0
13
local tr_me = 0
14
local blackList = {}
15
local pim = c.pim
16
local red = c.redstone
17
local mod = c.modem
18
term.clear() term.setCursor(1,1)
19
gpu.setResolution(80,25)
20
name = ''
21
local setting = {0,2,3,'north',4,5}--сундук обмена(тр);сундук сбоев(тр);зарядка rf;сторона пим; зарядка eu; зарядка газа;
22
local setting_me = {1,3,'up','2-5'}--сундук обмена(тр);МЭ;сторона куда скидывать из МЭ; коэфициэнт обработки
23
local admin = 'Asior'
24
local listOre = {}
25
local rHi = {'Приветствую', 'Салют', 'Даров', 'Hi', 'Здравствуйте', 'Дай краба', 'Ку', 'Хаюшки'}
26
local text = {}
27
mod.open(1)
28
mod.setWakeMessage('START')
29
nameTerm = ...
30
31
local setting_gpu_tr = {24,8}
32
local screen = {
33
  {{ --экран 1 авторизация
34
    visible = false,
35
    X = 33,
36
    Y = 11,
37
    W = 15,
38
    H = 1,
39
    color = 0x005500,
40
    textColor = 0xffffff,
41
    text = '[ Авторизация ]',
42
    action = function()
43
      if seachBlackList(nameUp) then
44
        unloadScreen(1)
45
        loadScreen(3)
46
        activBottom()
47
        blockUser()
48
        unloadScreen(3)
49
        loadScreen(1)
50
        activBottom()
51
        menu0()
52
      else
53
        name = nameUp
54
        logger(name,'Авторизация')
55
        logger('List_name',tostring(name))
56
        red.setOutput(0,255)
57
        unloadScreen(1)
58
        loadScreen(2)
59
        activBottom()
60
        menu1(name)
61
      end
62
    end
63
  },
64
  {
65
    visible = false,
66
    X = 34,
67
    Y = 13,
68
    W = 12,
69
    H = 1,
70
    color = 0x0000ff, --0x00aa00
71
    textColor = 0xffffff,
72
    text = '[ Лицензия ]',
73
    action = function()
74
      unloadScreen(1)
75
      loadScreen(4)
76
      activBottom()
77
      menu_L()
78
    end
79
  },
80
  {
81
    visible = false,
82
    X = 80,
83
    Y = 25,
84
    W = 1,
85
    H = 1,
86
    color = 0x000000, --0x00aa00
87
    textColor = 0xffffff,
88
    text = '╝',
89
    action = function()
90
      if nameUp == admin then
91
        logger(name,'Выход из программы')
92
        logger('List_name',tostring(nameUp)..' #########ВЫХОД#########')
93
        gpu.setBackground(b_color)
94
        gpu.setForeground(f_color)
95
        term.clear()
96
        com.addUser(admin)
97
        os.exit()
98
      end
99
    end
100
  }},
101
  {{ --экран 2 выбор действия
102
    visible = false,
103
    X = 31,
104
    Y = 6,
105
    W = 19,
106
    H = 1,
107
    color = 0x005500,
108
    textColor = 0xffffff,
109
    text = '[ Зарядка   вещей ]',
110
    action = function()
111
      logger(name,'****ЗАРЯДКА****')
112
      unloadScreen(2)
113
      loadScreen(3)
114
      activBottom()
115
      menu2()
116
      --os.sleep(3)
117
      clearCharg(name)
118
      charg()
119
      name = ''
120
      unloadScreen(3)
121
      loadScreen(1)
122
      activBottom()
123
      menu0()
124
      red.setOutput(0,0)
125
    end
126
  },
127
  {
128
    visible = false,
129
    X = 29,
130
    Y = 8,
131
    W = un.len('[ Обменник руды '..setting_me[4]..'Х ]'),
132
    H = 1,
133
    color = 0x005500, --0x00aa00
134
    textColor = 0xffffff,
135
    text = '[ Обменник руды '..setting_me[4]..'Х ]',
136
    action = function()
137
      logger(name,'****РУДООБМЕННИК****')
138
      unloadScreen(2)
139
      loadScreen(3)
140
      activBottom()
141
      menu3()
142
      ores()
143
      name = ''
144
      unloadScreen(3)
145
      loadScreen(1)
146
      activBottom()
147
      menu0()
148
      red.setOutput(0,0)
149
    end
150
  },
151
  {
152
    visible = false,
153
    X = 31,
154
    Y = 14,
155
    W = 19,
156
    H = 1,
157
    color = 0xff0000,
158
    textColor = 0xffffff,
159
    text = '[      Выход      ]',
160
    action = function()
161
      name = ''
162
      unloadScreen(2)
163
      loadScreen(1)
164
      activBottom()
165
      menu0()
166
      red.setOutput(0,0)
167
    end
168
  },
169
  {
170
    visible = false,
171
    X = 53,
172
    Y = 6,
173
    W = 5,
174
    H = 1,
175
    color = 0x005555,
176
    textColor = 0xffffff,
177
    text = '[ ? ]',
178
    action = function()
179
      gpu.setBackground(b_color)
180
      gpu.setForeground(f_color)
181
      gpu.fill(2, 16, 78, 9, ' ')
182
      menu1_sp(1)
183
    end
184
  },
185
  {
186
    visible = false,
187
    X = 53,
188
    Y = 8,
189
    W = 5,
190
    H = 1,
191
    color = 0x005555,
192
    textColor = 0xffffff,
193
    text = '[ ? ]',
194
    action = function()
195
      gpu.setBackground(b_color)
196
      gpu.setForeground(f_color)
197
      gpu.fill(2, 16, 78, 9, ' ')
198
      menu1_sp(2)
199
    end
200
  },
201
  },
202
  {{ --экран 3 пустышка для обменников
203
    visible = false,
204
    X = 36,
205
    Y = 18,
206
    W = 1,
207
    H = 1,
208
    color = 0xff0000,
209
    textColor = 0xffffff,
210
    text = '[ Выход ]',
211
    action = function()
212
    end
213
  }},
214
  {{ --экран 4 лицензия
215
    visible = false,
216
    X = 37,
217
    Y = 20,
218
    W = 7,
219
    H = 1,
220
    color = 0xff0000,
221
    textColor = 0xffffff,
222
    text = '[ Назад ]',
223
    action = function()
224
      name = ''
225
      unloadScreen(4)
226
      loadScreen(1)
227
      activBottom()
228
      menu0()
229
    end
230
  }},
231
  {{ --экран 5 экран торговли/продажи
232
    visible = false,
233
    X = 70,
234
    Y = 2,
235
    W = 9,
236
    H = 1,
237
    color = 0xff0000,
238
    textColor = 0xffffff,
239
    text = '[ Выход ]',
240
    action = function()
241
      name = ''
242
      unloadScreen(5)
243
      loadScreen(1)
244
      activBottom()
245
      red.setOutput(0,0)
246
      menu0()
247
      str = 1
248
    end
249
  },
250
  {
251
    visible = false,
252
    X = 3,
253
    Y = 24,
254
    W = 6,
255
    H = 1,
256
    color = 0x005500,
257
    textColor = 0xffffff,
258
    text = '[ ◄◄ ]',
259
    action = function()
260
      if str - 1 > 0 then
261
        str = str-1
262
      end
263
      tableProduct(str)
264
    end
265
  },
266
  {
267
    visible = false,
268
    X = 73,
269
    Y = 24,
270
    W = 6,
271
    H = 1,
272
    color = 0x005500,
273
    textColor = 0xffffff,
274
    text = '[ ►► ]',
275
    action = function()
276
      if str + 1 <= math.ceil(#baseT/34) then
277
        str = str+1
278
      end
279
      tableProduct(str)
280
    end
281
  },  
282
  {
283
    visible = false,
284
    X = 57,
285
    Y = 2,
286
    W = 11,
287
    H = 1,
288
    color = 0x005555,
289
    textColor = 0xffffff,
290
    text = '[ Продажа ]',
291
    action = function()
292
      
293
    end
294
  }, 
295
  }
296
}
297
tButtons = {}
298
299
local timezone = 3
300
local function getTime() --определение системного времени
301
  local file = io.open('/tmp/clock.dt', 'w')
302
  file:write('time')
303
  file:close()
304
  local lastmod = fs.lastModified('/tmp/clock.dt')/1000+3600*timezone   
305
  return os.date("%H:%M ", lastmod)
306
end
307
308
function logger(nm,sms) --логирование данных
309
  mod.broadcast(1,tostring(nm), getTime()..' '..nameTerm..' '..sms)
310
end
311
312
local function loadBaseBlackList()
313
  f = io.open('/home/listBlack.csv')
314
  local line = f:read()
315
  while line ~= nil do
316
    if line ~= '/n' then
317
      local vr = curPhrase(line)
318
      blackList[#blackList+1] = vr[1]
319
    end
320
    line = f:read()
321
  end
322
  f:close()
323
end
324
325
function seachBlackList(name)
326
  for i=1, #blackList do
327
    if blackList[i] == name then
328
      return true
329
    end
330
  end
331
  return false
332
end
333
334
local function readBaseTransposer() --подкгрузка базы транспозеров
335
  f = io.open('/home/listTransposer.csv')
336
  local line = f:read()
337
  local vr = curPhrase(line)
338
  f:close()
339
  tr = c.proxy(c.get(vr[1]))
340
  tr_me = c.proxy(c.get(vr[2]))
341
end
342
343
local function gpuSetLine(x,y,text)
344
  gpu.set(x,y,string.rep(' ', 78-x))
345
  gpu.set(x,y,tostring(text))
346
end
347
348
function blockUser()
349
  text = 
350
 {'░░░░░░░░░░░░░░║░░░░░░░░░░░░░░░░',
351
  '░░░░░▄█▀▄░░░░░║░░░░░░▄▀▄▄░░░░░░',
352
  '░░░░░░░░░▀▄░░░║░░░░▄▀░░░░░░░░░░',
353
  '░░░░▄▄▄░░░░█▄▄▄▄▄▄█░░░░▄▄▄░░░░░',
354
  '░░░▀░░░▀█░█▀░░▐▌░░▀█░█▀░░░▀░░░░',
355
  '░░░░░░░░░██░░▀▐▌▀░░██░░░░░░░░░░',
356
  '░░░░▄█▀▀▀████████████▀▀▀█░░░░░░',
357
  '░░░█░░░░░░██████████░░░░░▀▄░░░░',
358
  '░░░█▄░░░█▀░░▀▀▀▀▀▀░░▀█░░░▄█░░░░',
359
  '░░░░▀█░░░█░░░░░░░░░░█░░░█▀░░░░░',
360
  'Поглядел? Молодец, теперь вали.',
361
  'Для тебя магаз закрыт. Читор!',
362
  'Активация изъятия вещей через:',}
363
  for i=1,#text do
364
    gpuSetLine(28,4+i,text[i])
365
  end
366
  for i=8,1,-1 do
367
    gpuSetLine(28,18,i)
368
    os.sleep(0.7)
369
  end
370
  os.sleep(1)
371
  gpuSetLine(28,17,'Поверил ?? ахаха!')
372
  os.sleep(2)
373
  gpuSetLine(22,18,'В следующий раз поговоришь с турелью')
374
  os.sleep(3)
375
end
376
377
function numer() --отладка
378
  for i=1,25 do
379
    gpu.set(1,i,tostring(i))
380
  end
381
end
382
383
local function drawButton(n) -- функция рисования кнопки
384
  gpu.setBackground(tButtons[n].color) -- задаем цвет кнопки
385
  gpu.setForeground(tButtons[n].textColor) -- задаем цвет текста
386
  gpu.fill(tButtons[n].X, tButtons[n].Y, tButtons[n].W, tButtons[n].H, ' ') -- заливаем область
387
  gpu.set(tButtons[n].X+(tButtons[n].W/2)-(un.len(tButtons[n].text)/2), tButtons[n].Y+(tButtons[n].H/2), tButtons[n].text) -- пишем текст по центру
388
end
389
390
function toggleVisible(n) -- переключение видимости кнопки
391
  if tButtons[n].visible then -- если кнопка видима
392
    tButtons[n].visible = false -- отключаем
393
    gpu.setBackground(b_color) -- берем цвет фона, полученный при старте программы
394
    gpu.fill(tButtons[n].X, tButtons[n].Y, tButtons[n].W, tButtons[n].H, ' ') -- стираем кнопку
395
  else -- если кнопка не активна
396
    tButtons[n].visible = true -- активируем
397
    drawButton(n) -- запускаем отрисовку
398
  end
399
end
400
401
local function blink(n) -- мигание кнопки
402
  local temp = ''
403
  for i=tButtons[n].X, tButtons[n].W+tButtons[n].X-1 do
404
    temp = temp..gpu.get(i,tButtons[n].Y)
405
  end
406
  tButtons[n].color, tButtons[n].textColor = tButtons[n].textColor, tButtons[n].color -- меняем местами цвета фона и текста
407
  drawButton(n) -- отрисовываем кнопку
408
  os.sleep(0.09) -- делаем задержку
409
  tButtons[n].color, tButtons[n].textColor = tButtons[n].textColor, tButtons[n].color -- меняем цвета обратно
410
  drawButton(n) -- перерисовываем кнопку
411
  gpu.set(tButtons[n].X,tButtons[n].Y,temp)
412
  gpu.setBackground(b_color)
413
  gpu.setForeground(f_color)
414
end
415
416
function activBottom() --активатор кнопок
417
  for i = 1, #tButtons do
418
    toggleVisible(i) -- активируем каждую кнопку
419
  end
420
  gpu.setBackground(b_color)
421
  gpu.setForeground(f_color)
422
end
423
424
function unloadScreen(num) --деактиватор кнопок
425
  for i = 1, #tButtons do
426
    if tButtons[i].visible then
427
      tButtons[i].visible = false
428
    end
429
  end
430
end
431
432
local function posCent(num) --рассчет положения в раснении по центру
433
  return math.ceil(40 - num/2)
434
end
435
436
function menu0()
437
  text = {
438
  'Торгово-зарядный аппарат',
439
  'Только у нас! Коэфициэнт переработки руды '..setting_me[4]..'Х !',
440
  'Для перехода в магазин встаньте на ПИМ и авторизуйтесь'}
441
  for i=1,#text do
442
    gpu.set(posCent(un.len(text[i])),1+i,text[i])
443
  end
444
  text = {
445
  'ВСТАНЬТЕ НА ПИМ',
446
  ' █▀█        █▀█',
447
  ' █ █        █ █',
448
  '▀▄ ▄▀      ▀▄ ▄▀',
449
  '  ▀          ▀'}
450
  for i=1,#text do
451
    gpu.set(60,14+i,text[i])
452
  end
453
  text = {
454
  'Иногда проходят акции по обмену руды до 1 к 7!',
455
  'Если аппарат что-то не вернул обращаться к',
456
  'Asior или в дискорд Asior#0138.',
457
  'Нажимая кнопку авторизоваться, вы автоматически соглашаетесь с лицензией'}
458
  for i=1,#text do
459
    gpu.set(posCent(un.len(text[i])),20+i,text[i])
460
  end
461
end
462
463
function menu1(name)
464
  vr = rHi[math.random(1,#rHi)]..' '..tostring(name)..' !'
465
  gpu.set(posCent(un.len(vr)),2, vr)
466
  gpu.set(posCent(19),4,'Выберите категорию:')
467
  gpu.set(posCent(46),18,'Не знаете что выбрать? Нажмите на кнопку с "?"')
468
end
469
470
function menu1_sp(tupe)
471
  text = {}
472
  if tupe == 1 then
473
    text = {
474
    'Зарядка вещей - заряжает любой инструмент работающий на РФ,',
475
    'EУ, а так-же Газовые вещи. Омнитулы, винтовки, буры и многое другое!',
476
    'Какие вещи можно тут заряжать можно увидеть на стенде у входа.',
477
    'Зарядка проходит за 15 сек на электрических вещах и за 80 сек на газовых.',
478
    'Время может немного отличаться, в связи с лагами сервера.',
479
    'Для зарядки необходимо наступить на панель ПИМ и активировать кнопку зарядки',
480
    'НЕ ПОКИДАЙТЕ ПИМ ДО ОКОНЧАНИЯ ЗАРЯДКИ! За это с шансом в 10% вы можете',
481
    'получить очень ценный приз! Вплоть до ИРИДИЯ! БЕСПЛАТНО!'}
482
  elseif tupe == 2 then
483
    text = {
484
    'Обменник руды - уникальная технология обработки всех типов руд. (кроме урана)',
485
    'К сожалению данная технология несовершенна, универсальный алгоритм обработки',
486
    'сильно сбавляет точность обработки в связи с чем проходят сильные потери.',
487
    'Процент обработки руды ~'..setting_me[4]..'Х. Для обработки необходимо встать на ПИМ и',
488
    'активировать кнопку. Руда с 1 слота инвентаря будет автоматически извлечена,',
489
    'обработана и возвращена вам в виде слитков.',
490
    'Убедитесь что у вас достаточно свободного места!'}
491
  end
492
  for i=1,#text do
493
    gpu.set(2,16+i,text[i])
494
  end
495
end
496
497
function menu2()--зарядка оружия
498
  text = {
499
  'Спасибо что выбираете нашу зарядную станцию!',
500
  'Для зарядки положите рф инструмент в 1 слот ВАШЕГО ИНВЕНТАРЯ',
501
  'и встаньте на кнопку PIM. Инструмент будет автоматически извлечен,',
502
  'и по окончании зарядки вернется к вам в 1 слот.',
503
  'Длительность РФ/ЕУ зарядки 15 секунд, ГАЗ - 80 секунд',
504
  'Пожалуйста не сходите с PIM до окончания зарядки.',}
505
  for i=1,#text do
506
    gpu.set(posCent(un.len(text[i])),3+i,text[i])
507
  end
508
end
509
510
function menu_L()
511
  text = {
512
  'Лицензия',
513
  '1.1 Данный аппарат не контроллируется администрацией сервера',
514
  '1.2 Используя аппарат, вы автоматически даете разрешение на анализ 1 слота',
515
  '1.3 При сбое аппарата вы можете подать жалобу его владельцу "Asior"',
516
  'по контактам на главном экране.',
517
  '1.4 Выдача утерянных предметов, если их утеря доказана логами аппарата,',
518
  'и скриншотами потерпевшего, производится или по почте (foresty),',
519
  'или из рук владельца.',
520
  '1.5 Если ресурсы автомат выдал не вам, а вашему другу/знакомому/врагу/вору',
521
  'вся ответственность лежит на вас. Использовать автомат разрешено только',
522
  'одному игроку за сессию.',
523
  '1.6 Если вы меняете руду на слитки, для дальнейшей продажи в своем магазине,',
524
  'вы будете заблокированы владельцем данного обменного автомата. Игроки',
525
  'сообщившие о продаже слитков будут награждены.',
526
  'Лицензия составлена и закреплена от 25.10.2019. ©Asior'}
527
  gpu.set(posCent(un.len(text[1])),2,text[1])
528
  for i=2,#text do
529
    gpu.set(2,2+i,text[i])
530
  end
531
end
532
533
function menu3()
534
  text = {
535
  'Спасибо что выбираете нашу рудообменную станцию!',
536
  'Встаньте на кнопку ПИМ, в 1 слот ВАШЕГО ИНВЕНТАРЯ положите',
537
  'руду для обработки. Коэфициэнт переработки '..setting_me[4]..'Х'}
538
  for i=1,#text do
539
    gpu.set(posCent(un.len(text[i])),3+i,text[i])
540
  end
541
end
542
543
function curPhrase(line) --вырезка фразы с разделителем
544
  local tbl = {}
545
  for part in line:gmatch("[^;]+") do
546
    table.insert(tbl, part) 
547
  end
548
  return tbl
549
end
550
551
local function readBaseOre() --подкгрузка базы руды
552
  f = io.open('/home/listOre.csv')
553
  local line = f:read()
554
  while line ~= nil do
555
    if line ~= '/n' then
556
      local vr = curPhrase(line)
557
      listOre[#listOre+1] = {['fingerprint']={['dmg'] = tonumber(vr[1]), ['id'] = vr[2]}, ['raw'] = vr[3], ['name'] = vr[4],['kf'] = tonumber(vr[5])}
558
    end
559
    line = f:read()
560
  end
561
  f:close()
562
end
563
564
local function seachNameOre(name) --поисковик 
565
  for i=1,#listOre do
566
    if listOre[i].raw == name then
567
      return true, i
568
    end
569
  end
570
  return false
571
end
572
573
function resursesME()
574
  local temp = {'Количество руды для обмена:'}
575
  local vr = ''
576
  local all = me.getAvailableItems()
577
  for i=1, #all do
578
    for i1=1,#listOre do
579
      if listOre[i1].name ~= vr then
580
        if all[i].fingerprint.id==listOre[i1].fingerprint.id and all[i].fingerprint.dmg==listOre[i1].fingerprint.dmg then
581
          temp[#temp+1] = listOre[i1].name..'.....'..math.floor(all[i].size/listOre[i1].kf)..'...1 к '..listOre[i1].kf
582
          vr = listOre[i1].name
583
        end
584
      end
585
    end
586
  end
587
  for i=1,#temp do
588
    gpu.set(5,10+i,temp[i])
589
  end
590
end
591
592
local function screenError(text)
593
  com.beep(1000)
594
  gpuSetLine(2,2,'ERROR!!!')
595
  gpuSetLine(2,3,text)
596
  os.sleep(3)
597
end
598
599
local function itemTransfer(tp, mass)
600
  local err = 0
601
  local vr = 0
602
  if tp == 'InventoryImport' then
603
    repeat
604
      vr = pim.pushItem(setting[4],1,mass[1])
605
      err = err+1
606
      os.sleep(0.2)
607
    until err > 10 or vr == mass[1] --vr~=0
608
    logger(name,'Перемещение из инвентаря в обменник: '..tostring(vr))
609
    if err >= 10 and vr < mass[1] then
610
      screenError('Не смог забрать из инвентаря предмет')
611
      return false
612
    end
613
  elseif tp == 'ChargImport' then
614
    repeat
615
      vr = tr.transferItem(setting[1],mass[1],1)
616
      err = err+1
617
      os.sleep(0.2)
618
    until err > 10 or vr~=nil
619
    logger(name,'Перемещение из обменника в зарядку типа '..mass[2]..' статус:'..tostring(vr))
620
    if err >= 10 then
621
      screenError('Не смог переместить предмет из обменника в зарядку')
622
      return false
623
    end
624
  elseif tp == 'ChargExport' then
625
    repeat
626
      vr = tr.transferItem(mass[1],setting[1])
627
      err = err+1
628
    until err > 10 or vr~=nil
629
    logger(name,'Перемещение из зарядки в обменник: '..tostring(vr))
630
    if err >= 10 then
631
      screenError('Не смог переместить предмет из зарядки в обменник')
632
      return false
633
    end
634
  elseif tp == 'InventoryExport' then
635
    for i=1,54 do
636
      vr = pim.pullItem(setting[4],i)
637
      if vr>0 then
638
        logger(name,'Перемещение из обменника слот: '..i..' в инвентарь: '..vr)
639
        err = err + vr
640
      end
641
    end
642
    --print(err,mass[1],mass[1]-err)
643
    if err <= mass[1] then
644
      return false, mass[1]-err
645
    end
646
  elseif tp == 'TransferExportMe' then
647
    vr = tr_me.getStackInSlot(setting_me[1],1).name
648
    local tbl = {}
649
    for tmp in string.gmatch(vr,'[o,O]re') do
650
      table.insert(tbl, tmp)
651
    end
652
    if #tbl == 1 then
653
      repeat
654
        vr = tr_me.transferItem(setting_me[1],setting_me[2])
655
        err = err+1
656
        logger(name,'Перемещение руды из обменника в МЭ: '..tostring(vr))
657
      until vr == mass[1] or err > 10
658
    else
659
      err = 10
660
    end
661
    if err >= 10 then
662
      screenError('Не смог переместить предмет из обменника в МЭ')
663
      return false
664
    end
665
  end
666
  return true
667
end
668
669
function ores()
670
  local time = 0
671
  local vr = false
672
  local temp = {}
673
  resursesME()
674
  repeat
675
    local tEvent = {pull_e(1)} -- ждем клика
676
    if tEvent[1] == 'touch' or tEvent[1] == 'drop' then
677
      nameUp = tEvent[6]
678
      if nameUp == name or name == '' or nameUp == admin then
679
        for i = 1, #tButtons do -- перебираем все кнопки
680
          if tButtons[i].visible then -- если кнопка активна
681
            if tEvent[3] >= tButtons[i].X and tEvent[3] <= tButtons[i].X+tButtons[i].W-1 and tEvent[4] >= tButtons[i].Y and tEvent[4] <= tButtons[i].Y+tButtons[i].H-1 then -- если клик произведен в пределах кнопки
682
              blink(i) -- мигнуть кнопкой
683
              return
684
            end
685
          end
686
        end
687
      end
688
    elseif tEvent[1] == 'player_off' then
689
      blink(1)
690
      logger(name, 'Ушел с ПИМ')
691
      return
692
    else
693
      if pim.getInventorySize()>0 then
694
        gpuSetLine(10,8,'Сканирую 1 слот ...')
695
        if pim.getStackInSlot(1) then
696
          err, num = seachNameOre(pim.getStackInSlot(1).raw_name)
697
          if err then
698
            vr = pim.getInventoryName()
699
            if vr~='pim' and vr ~= name then
700
              gpuSetLine(10,8,'Вас слишком много на пим!')
701
              gpuSetLine(10,9,'Работа с автоматом строго по одному!')
702
              for i=1,3 do
703
                com.beep(1500,1)
704
              end
705
              logger(name,'Отбой. Много игроков на ПИМ. Сессия: '..name..' Долбаеб: '..vr)
706
              return
707
            end
708
            gpuSetLine(10,8,'Обнаружена руда ...')
709
            size = pim.getStackInSlot(1).qty
710
            logger(name,'Руда: '..listOre[num].raw..'; Количество: '..size)
711
            local all = me.getAvailableItems()
712
            for i=1, #all do
713
              if all[i].fingerprint.id==listOre[num].fingerprint.id and all[i].fingerprint.dmg==listOre[num].fingerprint.dmg then
714
                logger(name,'Найден металл в МЭ')
715
                if all[i].size >= math.floor(size*listOre[num].kf) then
716
                  logger(name,'Количество металла в МЭ: '..all[i].size)
717
                  if not itemTransfer('InventoryImport', {size}) then
718
                    gpuSetLine(10,8,'ПОПЫТКА ВЗЛОМА!')
719
                    os.sleep(3)
720
                    return
721
                  end
722
                  if not itemTransfer('TransferExportMe', {size}) then
723
                    gpuSetLine(10,8,'ОТКАЗ СИСТЕМЫ! СООБЩИТЕ ВЛАДЕЛЬЦУ!!!')
724
                    os.sleep(3)
725
                    return
726
                  end
727
                  size = math.floor(size*listOre[num].kf)
728
                  local sizeTm = size
729
                  repeat
730
                    vr = me.exportItem(all[i].fingerprint, setting_me[3], size)
731
                    logger(name,'Перемещение руды из МЭ в обменник: '..vr.size)
732
                    size = size - vr.size
733
                  until size <= 0
734
                  gpuSetLine(10,8,'Обработка завершена!')
735
                  for i=1,30 do
736
                    gpuSetLine(10,8,'Встаньте на ПИМ для получения слитков')
737
                    gpuSetLine(10,9,'Сброс сессии через '..(30-i)..' сек')
738
                    if pim.getInventorySize()>0 and pim.getInventoryName() == name then
739
                      vr, sizeTm = itemTransfer('InventoryExport', {sizeTm})
740
                      if not vr and sizeTm~=0 then
741
                        gpuSetLine(10,8,'Освободите 1 слот! Не могу выдать вам руду!')
742
                        com.beep(1000)
743
                      else
744
                        gpuSetLine(10,9,'Рудообработка завершена! Спасибо, что выбираете нас!')
745
                        os.sleep(1)
746
                        time = 0
747
                        break
748
                      end
749
                    end
750
                    os.sleep(1)
751
                  end
752
                  logger(name,'Сбой, нет игрока на ПИМ')
753
                else
754
                  gpuSetLine(10,8,'Металл закончился. Подождите пару минут.')
755
                end
756
              end
757
            end
758
          else
759
            gpuSetLine(10,8,'Руда не обнаружена!')
760
          end
761
        else
762
          gpuSetLine(10,8,'Положите в 1 слот руду')
763
        end
764
      end
765
      gpuSetLine(10,9,'Завершение сессии через '..30-time..' сек')
766
      time = time + 1
767
    end
768
  until time > 30
769
  logger(name,'Отбой. Игрок не наступил на ПИМ')
770
  return
771
end
772
773
local function borders()
774
  gpu.set(2, 1, string.rep('═', 78))
775
  gpu.set(2, 25, string.rep('═', 78))
776
  gpu.set(1, 2, string.rep('║', 23),true)
777
  gpu.set(80, 2, string.rep('║', 23),true)
778
  gpu.set(1, 1, '╔')
779
  gpu.set(80, 1, '╗')
780
  gpu.set(1, 25, '╚')
781
  gpu.set(80, 25, '╝')
782
end
783
784
function loadScreen(num)
785
  gpu.setBackground(b_color)
786
  gpu.setForeground(f_color)
787
  gpu.fill(1, 1, W, H, ' ')
788
  tButtons = {}
789
  tButtons = screen[num]
790
  borders()
791
  --numer()
792
end
793
794
function clearCharg() --для очистки если че сломалось
795
  if tr.transferItem(setting[3],setting[2])>0 then
796
    logger('List_name','Обнуление из зарядки рф')
797
  end
798
  if tr.transferItem(setting[5],setting[2])>0 then
799
    logger('List_name','Обнуление из зарядки еу')
800
  end
801
  if tr.transferItem(setting[6],setting[2])>0 then
802
    logger('List_name','Обнуление из зарядки газа')
803
  end
804
  for i=1, 54 do
805
    if tr.transferItem(setting[1],setting[2],1)>0 then
806
      logger('List_name','Обнуление из обменника')
807
    end
808
  end
809
end
810
811
local function seachName(name)
812
  local rf = {'mo:omni_tool', 'mo:phaser', 'mo:phaser_rifle', 'mo:plasma_shotgun', 'mo:ion_sniper','simplyjetpacks:jetpacks', 'simplyjetpacks:jetpacksEIO', 'Mekanism:FreeRunners'}
813
  local ic = {'IC2:itemToolDrill', 'IC2:itemToolDDrill', 'IC2:itemToolChainsaw', 'IC2:itemToolWrenchElectric', 'IC2:itemTreetapElectric','IC2:itemArmorJetpackElectric', 'IC2:itemBatRE'}
814
  local mk = {'Mekanism:Jetpack', 'Mekanism:ArmoredJetpack', 'Mekanism:Flamethrower'}
815
  for i=1,#rf do
816
    if rf[i] == name then
817
      return true, 'rf'
818
    end
819
  end
820
  for i=1,#ic do
821
    if ic[i] == name then
822
      return true, 'ic'
823
    end
824
  end
825
  for i=1,#mk do
826
    if mk[i] == name then
827
      return true, 'mk'
828
    end
829
  end
830
  return false
831
end
832
833
function charg() --зарядка с поиском
834
  local time = 0
835
  local vr = false
836
  repeat
837
    local tEvent = {pull_e(1)} -- ждем клика
838
    if tEvent[1] == 'touch' or tEvent[1] == 'drop' then
839
      nameUp = tEvent[6]
840
      if nameUp == name or name == '' or nameUp == admin then
841
        for i = 1, #tButtons do -- перебираем все кнопки
842
          if tButtons[i].visible then -- если кнопка активна
843
            if tEvent[3] >= tButtons[i].X and tEvent[3] <= tButtons[i].X+tButtons[i].W-1 and tEvent[4] >= tButtons[i].Y and tEvent[4] <= tButtons[i].Y+tButtons[i].H-1 then -- если клик произведен в пределах кнопки
844
              blink(i) -- мигнуть кнопкой
845
              return
846
            end
847
          end
848
        end
849
      end
850
    else
851
      if pim.getInventorySize()>0 then
852
        if pim.getStackInSlot(1) then
853
          item, tupe = seachName(pim.getStackInSlot(1).id)
854
          if item then
855
            vr = pim.getInventoryName()
856
            if vr~='pim' and vr ~= name then
857
              gpuSetLine(10,14,'Вас слишком много на пим!')
858
              gpuSetLine(10,15,'Работа с автоматом строго по одному!')
859
              for i=1,3 do
860
                com.beep(1500,1)
861
              end
862
              logger(name,'Отбой. Много игроков на ПИМ. Сессия: '..name..' Долбаеб: '..vr)
863
              return
864
            end
865
            logger(name,'Обнаружен инструмент: '..pim.getStackInSlot(1).id)
866
            gpuSetLine(10,14,'Инструмент подходит под тип зарядки')
867
            if not itemTransfer('InventoryImport', {1}) then
868
              gpuSetLine(10,14,'ОТКАЗ СИСТЕМЫ! СООБЩИТЕ ВЛАДЕЛЬЦУ!!!')
869
              os.sleep(3)
870
              return
871
            end
872
            local sl = 15
873
            local side = setting[1] 
874
            if tupe == 'rf' then
875
              side = setting[3]
876
            elseif tupe == 'ic' then
877
              side = setting[5]
878
            else
879
              side = setting[6]
880
              sl = 80
881
            end
882
            if not itemTransfer('ChargImport', {side, tupe}) then
883
              gpuSetLine(10,14,'ОТКАЗ СИСТЕМЫ! СООБЩИТЕ ВЛАДЕЛЬЦУ!!!')
884
              os.sleep(3)
885
              return
886
            end
887
            gpuSetLine(10,14,'Выполняется зарядка, оставайтесь на ПИМ')
888
            for i=1,sl do
889
              gpuSetLine(10,15,'До окончания зарядки '..sl-i..' сек')
890
              os.sleep(1)
891
            end
892
            if not itemTransfer('ChargExport', {side}) then
893
                  gpuSetLine(10,14,'ОТКАЗ СИСТЕМЫ! СООБЩИТЕ ВЛАДЕЛЬЦУ!!!')
894
                  os.sleep(3)
895
                  return
896
                end
897
            for i=1,30 do
898
              gpuSetLine(10,14,'Встаньте на ПИМ для возврата инструмента')
899
              gpuSetLine(10,15,'Сброс сессии через '..(30-i)..' сек')
900
              vr = pim.getInventoryName()
901
              if vr~='pim' and vr ~= name then
902
                gpuSetLine(10,14,'Вас слишком много на пим! '..name..', наступите на ПИМ!')
903
                com.beep(1500,1)
904
                logger(name,'Попытка перехвата. Сессия: '..name..' Долбаеб: '..vr)
905
              elseif pim.getInventorySize()>0 and vr == name then
906
                sizeTm = 1
907
                vr, sizeTm = itemTransfer('InventoryExport', {sizeTm})
908
                if not vr and sizeTm~=0 then
909
                  gpuSetLine(10,14,'Освободите 1 слот! Не могу вернуть вам инструмент!')
910
                  com.beep(1000)
911
                else
912
                  gpuSetLine(10,14,'')
913
                  gpuSetLine(10,15,'Зарядка завершена! Удачи и спасибо, что выбираете нас!')
914
                  os.sleep(3)
915
                  return
916
                end
917
              end
918
              os.sleep(0.7)
919
            end
920
            logger(name,'Сбой, нет игрока на ПИМ')
921
          end
922
        else
923
          gpuSetLine(10,14,'В 1 слоте нет инструмента для зарядки')
924
        end
925
      else
926
        gpuSetLine(10,14,'Положите в 1 слот инструмент для зарядки')
927
      end
928
    end
929
    gpuSetLine(10,15,'Завершение сессии через '..30-time..' сек')
930
    time = time + 1
931
  until time > 30
932
  logger(name,'Отбой. Игрок не наступил на ПИМ')
933
  return
934
end
935
------------------------------------------------------
936
937
require("process").info().data.signal = function() end
938
939
if not fs.exists('/log') then
940
  fs.makeDirectory('/log')
941
end
942
while com.users() do
943
  com.removeUser(com.users())
944
end
945
logger('List_name','######СТАРТ ПРОГРАММЫ#######')
946
logger('List_name','######Чтение базы руды######')
947
readBaseOre()
948
logger('List_name','##Чтение базы транспозеров##')
949
readBaseTransposer()
950
logger('List_name','##Чтение базы заблоченных###')
951
loadBaseBlackList()
952
logger('List_name','####Загрузка интерфейса#####')
953
str = 1
954
trade = 1
955
loadScreen(1)
956
menu0()
957
activBottom()
958
name = ''
959
local cl = 0
960
while true do
961
  local tEvent = {pull_e(1)} -- ждем клика
962
  if tEvent[1] == 'modem_message' then
963
    if tEvent[6] == 'infoDrop' and tEvent[7] == nameTerm then
964
      local data = tr.getAllStacks(setting[2]).getAll()
965
      vr = ''
966
      for i=0,#data do
967
        if data[i].label then
968
          vr = vr..'#'..(i+1)..':'..data[i].label..' '
969
        end
970
      end
971
      mod.broadcast(1,'infoDropReturn', nameTerm, vr)
972
      vr = 0
973
      data = 0
974
    elseif tEvent[6] == 'reboot' and tEvent[7] == nameTerm then
975
      logger('List_name','####Удаленная перезагрузка#####')
976
      mod.broadcast(1,'rebootReturn', nameTerm)
977
      com.shutdown(true)
978
    elseif tEvent[6] == 'PING' and tEvent[7] == nameTerm then
979
      mod.broadcast(1,'PONG', nameTerm)
980
    end
981
  end
982
  if tEvent[1] == 'player_on' then --нажатие на ПИМ должно сработать как кнопка авторизации
983
    nameUp = tEvent[2]
984
    if name == '' then
985
      blink(1)
986
      cl = 0
987
      tButtons[1].action() -- выполнить назначенный код
988
    end
989
  end
990
  if tEvent[1] == 'touch' then
991
    nameUp = tEvent[6]
992
    if nameUp == name or name == '' or nameUp == admin then
993
      for i = 1, #tButtons do -- перебираем все кнопки
994
        if tButtons[i].visible then -- если кнопка активна
995
          if tEvent[3] >= tButtons[i].X and tEvent[3] <= tButtons[i].X+tButtons[i].W-1 and tEvent[4] >= tButtons[i].Y and tEvent[4] <= tButtons[i].Y+tButtons[i].H-1 then -- если клик произведен в пределах кнопки
996
            blink(i) -- мигнуть кнопкой
997
            cl = 0
998
            tButtons[i].action() -- выполнить назначенный код
999
            break
1000
          end
1001
        end
1002
      end
1003
    end
1004
  else
1005
    cl = cl+1
1006
    if cl > 30 then
1007
      if name~= '' then
1008
        name = ''
1009
        unloadScreen(2)
1010
        loadScreen(1)
1011
        activBottom()
1012
        menu0()
1013
        red.setOutput(0,0)
1014
      end
1015
      cl = 0
1016
      red.setOutput(0,0)
1017
    end
1018
  end
1019
end
1020
1021
--all = me.getAvailableItems()
1022
--me.exportItem(all[1].fingerprint, DIR, 1, rSlot)