forked from PenisBlistashiq/Rust-plugins-236-240-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDuel.cs
More file actions
4746 lines (4349 loc) · 194 KB
/
Copy pathDuel.cs
File metadata and controls
4746 lines (4349 loc) · 194 KB
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("Duel", "RustPlugin.ru", "4.2.62")]
[Description("Automatic Duel (Bets) with GUI, weapons list, auto-created arenas, save players loot and position")]
class Duel : RustPlugin
{
#region Messages&Config
string notAllowed = "Вызов на дуэль запрещен";
string duelCommand = "<color=orange>/duel <ник></color> - вызвать игрока на дуэль\n<color=orange><color=#ADFF2F>/duels</color> <ник></color> - <color=#ADFF2F>вызвать игрока на дуэль со ставками</color>\n<color=orange>/duel a</color> - принять вызов\n<color=orange>/duel c</color> - отменить вызов\n<color=orange>/duel stat</color> - статистика\n<color=orange>/duel top</color> - топ\nКомандная дуэль:\n<color=orange>/duel create [2-6]</color> - создать командную дуэль\n<color=orange>/duel join red/blue</color> - подать заявку\n<color=orange>/duel accept</color> - принять в дуэль (для создателя)\n<color=orange>/duel c</color> - покинуть дуэль";
string dontHaveRequest = "У вас нет заявок на дуэль";
string notFoundPlayer = "Игрок с именем <color=#7b9ef6>{0}</color> не найден";
string alreadyHaveDuel = "<color=#7b9ef6>{0}</color> уже имеет активную дуэль";
string youOnDuel = "Вы уже имеете активную дуэль";
string noArenas = "Извините, все арены сейчас заняты";
string noBuildAcess = "Вы должны быть авторизованы в шкафу";
string cooldownMessage = "Вы сможете вызвать на дуэль через {0} секунд";
string createRequest = "Вы вызвали <color=#7b9ef6>{0}</color> на дуэль!\n<color=orange>/duel c</color> - отменить вызов";
string receiveRequest = "<color=#7b9ef6>{0}</color> вызвал вас на дуэль!\n<color=orange>/duel a</color> - принять вызов\n15 секунд до отмены\n<color=orange>/duel c</color> - отменить вызов";
string youDontHaveRequest = "У вас нет активных вызовов";
string cantCancelDuel = "Невозможно отменить начавшуюся дуэль.\nПобеди своего противника!";
static string duelHasBeenCancelled = "Дуэль c <color=#7b9ef6>{0}</color> отменена.";
static string duelStart = "Дуэль началась!";
static string playerNotFound = "Игрок с именем {0} не найден";
static string foundMultiplePlayers = "Найдено несколько игроков: <color=#7b9ef6>{0}</color>";
static string guiChooseWeapon = "Выберите оружие из списка";
static string guiYourChoose = "Вы выбрали: {0}";
static string guiWaitForOpponentChoose = "Противник выбирает оружие";
static string guiOpponentsWeapon = "Противник выбрал: {0}";
static string guiStartAboutToBegin = "Начало через несколько секунд";
static string guiSurrenderButton = "Сдаться";
static string guiAutoCloseSec = "До выбора случайного оружия: {0}";
static string guiPlayerSleep = "Ожидаем пока соперник проснётся";
string statLoss = "Тебе засчитано поражение в дуэли";
string statWin = "Тебе засчитана победа в дуэли";
string notificationAboutWin = "[Дуэль] <color=#7b9ef6>{0}</color> vs <color=#7b9ef6>{1}</color>\nПобедитель: <color=#7b9ef6>{2}</color>";
string cantBuild = "Ты не можешь строить на дуэли";
string cantUseRecycle = "Ты не можешь использовать переработчик на дуэли";
string cantUseNexusKits = "Ты не можешь использовать киты на дуэли";
string cantTrade = "Ты не можешь обмениваться на дуэли";
string cantRemove = "Ты не можешь ремувать на дуэли";
string cantTp = "Ты не можешь пользоваться телепортом на дуэли";
string cantUseKit = "Ты не можешь получить кит на дуэли";
string cantUseCommand = "Вы не можете использовать /{0} на Duel";
string cantUseBackPack = "Ты не можешь использовать рюкзак на дуэли";
string cantUseSkins = "Ты не можешь использовать скины на дуэли";
string cantUseKill = "Ты не можешь использовать kill на дуэли";
string yourStat = "Ваша статистика по дуэлям:\nПобед: {0}\nПоражений: {1}\nКомандные дуэли:\nПобед:{2}\nПоражений:{3}";
string emptyTop = "Статистика пуста как твоя кровать по ночам";
string topWin = "Топ побед в дуэлях:";
string topTeamWin = "\n\nТоп побед в командных дуэлях:";
string topLosses = "\n\nТоп поражений в дуэлях:";
string topTeamLoss = "\n\nТоп поражений в командных дуэлях:";
string playerInTop = "\n{0}. <color=#469cd0>{1}</color>: {2}"; // номер. ник: значение
static string returnPlayerReason = "Дуэль окончена.\nПричина: <color=orange>{0}</color>";
static string returnReasonSleep = "Кто-то слишком долго спал";
static string returnReasonGUIFail = "Кто-то слишком долго выбирает оружие";
static string returnReasonLimitTime = "Время на дуэль вышло({0} секунд)";
static string returnReasonDisconnect = "Соперник отключился";
static string returnReasonSurrender = "Кто-то всё же решил сдаться";
static string returnReasonUnload = "Плагин на время отключен. Попробуйте позже.";
static string teamDuelCancelled = "Командная дуэль отменена\nПричина: не собрана за {0} сек";
static string teamPlayerDisconnect = "[Дуэль] <color=#7b9ef6>{0}</color> вышел с сервера!";
static string teamWinRed = "[Дуэль] Побеждает команда <color=red>RED</color>!";
static string teamWinBlue = "[Дуэль] Побеждает команда <color=blue>BLUE</color>!";
static string teamDuellerWounded = "[Дуэль] Один из дуэлянтов ранен.\nДуэль не начнётся, пока он ранен.";
static string teamArensBusy = "[Дуэль] Пожалуйста, подождите. Все арены заняты.";
static string teamCooldownToCreate = "Вы сможете создать командную дуэль через {0} сек";
static string teamAlreadyCreated = "Извините, но командная дуэль уже создана. Присоединиться: /duel join red/blue";
static string teamCreatedPermPref = "<color=yellow> Турнирную </color>";
static string teamSucessCreated = "<color=#409ccd>{0}</color> создал{1}командную дуэль <color=#36978e>{2}</color> на <color=#36978e>{2}</color>!\nПодать заявку на участие в команде <color=red>RED</color>: /duel join red\nПодать заявку на участие в команде <color=blue>BLUE</color>: /duel join blue";
static string teamCancelDuel = "Отменить дуэль: <color=orange>/duel c</color>";
static string teamNotOwner = "Ты не создатель дуэли";
static string teamNoSlotsBlue = "Свободных мест в команде blue нет";
static string teamNoSlotsRed = "Свободных мест в команде red нет";
static string teamJoinPermPref = "<color=yellow> Турнирная </color>";
static string teamJoinRedPref = "<color=red>red</color>";
static string teamJoinBluePref = "<color=blue>blue</color>";
static string teamAboutToBegin = "[Дуэль] Начало через 5 секунд!";
static string teamJoinAboutToBeginAnnounce = "[{0}Командная дуэль]\n<color=#7b9ef6>{1}</color> присоединился к команде {2}\nНабор окончен!\nДуэль скоро начнется";
static string teamJoinAnnounce = "[{0}Командная дуэль]\n<color=#7b9ef6>{1}</color> присоединился к команде {2}\nСвободных мест:\n<color=red>red</color>: {3}\n<color=blue>blue</color>: {4}\nПодать заявку: <color=orange>/duel join red</color> или <color=orange>blue</color>";
static string teamPlayerWont = "{0} не подавал заявку на дуэль";
static string teamErrorNoCommand = "Ошибка. Выберите команду: /duel join red / blue";
static string teamAlreadyRequest = "Вы уже подали заявку на командную дуэль. Ждите одобрения создателя";
static string teamAlreadyStarted = "Ошибка. Дуэль уже началась!";
static string teamNoPerm = "Извините, у вас нет доступа к турнирным дуэлям.\nПриобрести можно в магазине сервера.";
static string teamSucessRequest = "Вы подали заявку.\nОжидайте, пока <color=#409ccd>{0}</color> одобрит её.\n<color=orange>/duel c</color> - отменить заявку.";
static string teamNewRequest = "<color=#409ccd>{0}</color> подал заявку на вступление в дуэль[<color={1}>{1}</color>].\n<color=orange>/duel accept</color> <color=#409ccd>{0}</color> - принять\nСписок подавших заявку: <color=orange>/duel accept</color>";
static string teamNoDuelsHowCreate = "Активных командных дуэлей нет. /duel create - создать новую";
static string teamGuiWeapons = "Оружие дуэлянтов: ";
static string teamGuiNoWeapon = "не выбрал";
static string teamGuiBluePlayerColor = "#76b9d6";
static string teamGuiRedPlayerColor = "red";
static string teamGuiWeaponColor = "#e0e1e3";
static string teamGuiWaiting = "Ожидаем других игроков\n60 секунд максимум";
static string teamDamageTeammate = "<color=#7b9ef6>{0}</color>: Эй! Я твой союзник!";
static string teamDeath = "[Дуэль] <color=#7b9ef6>{0}</color> [<color={1}>{1}</color>] погиб!\n<color=blue>Team Blue</color>: {2} человек\n<color=red>Team Red</color>: {3} человек";
static float teamDuelRequestSecToClose = 300;
float cooldownTeamDuelCreate = 180f;
float cooldownRequestSec = 60;
static float requestSecToClose = 20;
static float duelMaxSec = 300;
static float chooseWeaponMaxSec = 25f;
static float teamChooseWeaponMaxSec = 60f;
int maxWinsTop = 5;
int maxLoseTop = 5;
static bool debug = true;
#endregion
#region Variables
[PluginReference]
Plugin Trade;
static string duelJoinPermission = "duel.join";
static string duelCreatePermission = "duel.create";
private readonly int triggerLayer = LayerMask.GetMask("Trigger");
bool isIni = false;
static List<ActiveDuel> createdDuels = new List<ActiveDuel>();
static List<TeamDuel> createdTeamDuels = new List<TeamDuel>();
static List<ulong?> toRemoveCorpse = new List<ulong?>();
Dictionary<ulong, float> lastRequestTime = new Dictionary<ulong, float>();
Dictionary<ulong, float> lastTeamDuelCreateTime = new Dictionary<ulong, float>();
static Dictionary<string, ulong> Wears = new Dictionary<string, ulong> //item shortname : skinid
{
{"metal.facemask", 0}, //shirt
{"metal.plate.torso", 0}, // Hat
{"shoes.boots", 0}, // Pants
{"hoodie", 0}, // Boots
{"pants", 0}, // tolsovka
{"roadsign.kilt", 0} // dorognie znaki
};
static Dictionary<string, ulong> WearsBlue = new Dictionary<string, ulong> //item id : skinid
{
{"metal.facemask", 0}, //hoodie
{"metal.plate.torso", 0}, // Hat
{"shoes.boots", 0}, // Pants
{"hoodie", 0}, // Boots
{"pants", 14178}, // tolsovka
{"roadsign.kilt", 0} // dorognie znaki
};
static Dictionary<string, ulong> WearsRed = new Dictionary<string, ulong> //item id : skinid
{
{"metal.facemask", 0}, //hoodie
{"metal.plate.torso", 0}, // Hat
{"shoes.boots", 0}, // Pants
{"hoodie", 0}, // Boots
{"pants", 0}, // tolsovka
{"roadsign.kilt", 0} // dorognie znaki
};
private List<BaseEntity> ArenaEntities = new List<BaseEntity>();
#endregion
#region Helperss
[PluginReference]
Plugin NoEscape;
bool IsRaidBlock(BasePlayer player)
{
if (plugins.Exists("NoEscape"))
{
var block = (bool)NoEscape?.Call("IsRaidBlocked", player);
if (block)
{
SendReply(player, "У Вас рейдблок, Duel запрещена");
return true;
}
}
return false;
}
#endregion
#region ChatCommand
[ChatCommand("duel")]
void chatduel(BasePlayer player, string command, string[] arg)
{
if (!isIni)
{
SendReply(player, "<color=#FE5256>Duel не инициирована. Ожидайте........ </color>");
return;
}
if (arg.Length == 0)
{
SendReply(player, duelCommand);
return;
}
if (IsRaidBlock(player)) return;
if (player.metabolism.radiation_poison.value > 5)
{
SendReply(player, "У Вас облучение радиацией. Duel запрещена");
return;
}
string aim = (string)arg[0];
if (aim == "join")
{
if (!canAcceptRequest(player)) return;
if (IsDuelPlayer(player))
{
player.ChatMessage("Вы уже дуэлянт");
return;
}
if (arg.Length == 2)
{
string team = (string)arg[1];
if (team != null)
JoinTeamDuel(player, team);
return;
}
else
{
if (createdTeamDuels.Count > 0)
{
var teamDuel = createdTeamDuels[0];
player.ChatMessage($"Ошибка. Укажите команду, к которой хотите присоединиться\nВ команде red: {teamDuel.playersAmount - teamDuel.teamred.Count} свобоных мест\nВ команде blue: {teamDuel.playersAmount - teamDuel.teamblue.Count} свобоных мест");
return;
}
else
{
player.ChatMessage("Ошибка. Пишите:\n/duel join red - присоединиться к команде red\n/duel join blue - присоединиться к команде blue");
return;
}
}
}
if (aim == "accept")
{
if (arg.Length == 2)
{
string requester = (string)arg[1];
var target = FindPlayersSingle(requester, player);
if (target != null)
AcceptRequestTeamDuel(player, target);
return;
}
else
{
if (createdTeamDuels.Count > 0)
{
string msg = "";
var teamDuel = createdTeamDuels[0];
if (teamDuel.owner != player)
{
player.ChatMessage("Ты не создатель дуэли");
return;
}
if (teamDuel.requestPlayers.Count > 0)
{
foreach (var pl in teamDuel.requestPlayers)
{
msg += $"<color=#409ccd>{pl.Key.displayName}</color>, ";
}
player.ChatMessage($"Игроки, подавшие заявку: {msg}\nПринять: <color=orange>/duel accept</color> <color=#409ccd>name</color>");
return;
}
else
{
player.ChatMessage("Список с заявками пуст.");
return;
}
}
else
{
player.ChatMessage("Командная дуэль не создана");
return;
}
}
}
if (aim == "create")
{
if (!CanCreateDuel(player, true)) return;
if (arg.Length >= 2)
{
string amount = (string)arg[1];
int intamount = 0;
if (Int32.TryParse(amount, out intamount))
{
if (intamount > 1 && intamount <= 6)
{
if (arg.Length == 3)
{
string perm = (string)arg[2];
if (perm == "perm")
{
if (!HavePerm(duelCreatePermission, player.userID)) return;
createTeamDuel(player, intamount, true);
return;
}
}
createTeamDuel(player, intamount);
return;
}
else
{
player.ChatMessage("Ошибка. Количество игроков в команде должно быть от 2 до 6");
return;
}
}
return;
}
else
{
player.ChatMessage("Ошибка. Укажите количество участников (от 2 до 6) в каждой команде\n/duel create [2-6]");
return;
}
}
if (aim == "top")
{
showTop(player);
return;
}
if (aim == "stat")
{
showStat(player);
return;
}
if (aim == "c")
{
CancelRequest(player);
return;
}
if (aim == "a")
{
if (createdTeamDuels.Count > 0)
{
var teamDuel = createdTeamDuels[0];
if (teamDuel.requestPlayers.ContainsKey(player))
{
player.ChatMessage("Ты подал заявку на командную дуэль.\nНачать новую ты не можешь");
return;
}
}
if (!canAcceptRequest(player)) return;
if (!IsDuelPlayer(player))
{
SendReply(player, dontHaveRequest);
return;
}
if (IsPlayerOnActiveDuel(player))
{
player.ChatMessage("Вы уже находитесь на дуэли.");
return;
}
AcceptRequest(player);
return;
}
var victim = FindPlayersSingle(aim, player);
if (victim != null)
{
if (createdTeamDuels.Count > 0)
{
var teamDuel = createdTeamDuels[0];
if (teamDuel.requestPlayers.ContainsKey(player))
{
player.ChatMessage("Ты подал заявку на командную дуэль.\nНачать новую ты не можешь");
return;
}
}
if (createdTeamDuels.Count > 0)
{
var teamDuel = createdTeamDuels[0];
if (teamDuel.requestPlayers.ContainsKey(victim))
{
player.ChatMessage("Невозможно вызвать этого игрока");
return;
}
}
if (createdTeamDuels.Count > 0)
{
var teamDuel = createdTeamDuels[0];
if (teamDuel.owner == victim)
{
player.ChatMessage("Невозможно вызвать этого игрока");
return;
}
}
if (victim == player)
{
player.ChatMessage("Вы не можете вызвать самого себя на дуэль");
return;
}
if (!CanCreateDuel(player)) return;
string reason = CanDuel(victim);
if (reason != null)
{
SendReply(player, reason);
return;
}
CreateRequest(player, victim);
return;
}
}
#endregion
#region Checks
bool IsArenaZone(Vector3 pos)
{
foreach (var arena in arenaList)
{
if (Vector3.Distance(pos, arena.pos) < 100)
return true;
}
return false;
}
void RemoveGarbage(BaseEntity entity)
{
if (entity == null) return;
if (entity?.net?.ID == null) return;
if (!isIni) return;
if (entity.transform.position.y > 450f && IsArenaZone(entity.transform.position))
{
var cont = entity as DroppedItemContainer;
if (cont != null)
{
cont.ResetRemovalTime(0.1f);
}
var corpse = entity as BaseCorpse;
if (corpse != null)
{
if (toRemoveCorpse.Count == 0) return;
if (corpse)
{
if ((corpse is PlayerCorpse) && corpse?.parentEnt?.ToPlayer())
{
if (corpse?.parentEnt?.ToPlayer() != null)
{
if (toRemoveCorpse.Contains(corpse?.parentEnt?.ToPlayer().userID))
{
corpse.ResetRemovalTime(0.1f);
toRemoveCorpse.Remove(corpse?.parentEnt?.ToPlayer().userID);
return;
}
}
}
}
}
if (entity is PlayerCorpse || entity.name.Contains("item_drop_backpack"))
{
NextTick(() =>
{
if (entity != null && !entity.IsDestroyed)
{
entity.Kill();
}
});
}
if (entity is WorldItem)
{
if ((entity as WorldItem).item.GetOwnerPlayer() == null) return;
var activeDuel = PlayersActiveDuel((entity as WorldItem).item.GetOwnerPlayer().userID);
if (activeDuel != null)
{
activeDuel.dropedWeapons.Add((entity as WorldItem).item);
return;
}
if (NeedToRemoveFromTeamDuel((entity as WorldItem).item.GetOwnerPlayer().userID))
{
createdTeamDuels[0].droppedWeapons.Add((entity as WorldItem).item);
}
}
}
}
bool NeedToRemoveFromTeamDuel(ulong? userid)
{
if (createdTeamDuels.Count > 0)
{
if (createdTeamDuels[0].allPlayers.Find(x => x.player.userID == userid))
return true;
}
return false;
}
ActiveDuel PlayersActiveDuel(ulong? userid)
{
if (createdDuels.Count == 0) return null;
foreach (var duel in createdDuels)
{
if (duel.player1.player.userID == userid && duel.player1.haveweapon)
{
return duel;
}
if (duel.player2.player.userID == userid && duel.player2.haveweapon)
{
return duel;
}
}
return null;
}
bool NeedToRemoveGarbage(ulong? userid)
{
int createdDuelsN = createdDuels.Count;
if (createdDuelsN == 0) return false;
if (createdDuels.Find(x => x.player1.player.userID == userid || x.player2.player.userID == userid)) return true;
return false;
}
bool IsDuelPlayer(BasePlayer player)
{
DuelPlayer dueller = player?.GetComponent<DuelPlayer>();
if (dueller == null) return false;
return true;
}
bool IsPlayerOnActiveDuel(BasePlayer player)
{
DuelPlayer dueller = player?.GetComponent<DuelPlayer>();
if (dueller == null) return false;
if (!dueller.canDoSomeThings) return true;
return false;
}
string CanDuel(BasePlayer player)
{
if (IsDuelPlayer(player))
{
return String.Format(alreadyHaveDuel, player.displayName);
}
if (busyArena.Count == arenaList.Count)
{
return noArenas;
}
return null;
}
bool canAcceptRequest(BasePlayer player)
{
if (player.IsDead())
{
return false;
}
if (player.IsWounded())
{
SendReply(player, notAllowed);
return false;
}
if (busyArena.Count == arenaList.Count)
{
SendReply(player, noArenas);
return false;
}
return true;
}
bool CanCreateDuel(BasePlayer player, bool isTeamDuel = false)
{
float value = 0;
if (lastRequestTime.TryGetValue(player.userID, out value) && !isTeamDuel)
{
if (UnityEngine.Time.realtimeSinceStartup - value < cooldownRequestSec)
{
float when = cooldownRequestSec - (UnityEngine.Time.realtimeSinceStartup - value);
player.ChatMessage(String.Format(cooldownMessage, (int)when));
return false;
}
}
if (player.IsWounded())
{
SendReply(player, notAllowed);
return false;
}
if (IsDuelPlayer(player))
{
SendReply(player, youOnDuel);
return false;
}
if (busyArena.Count == arenaList.Count)
{
SendReply(player, noArenas);
return false;
}
if (!isTeamDuel)
lastRequestTime[player.userID] = UnityEngine.Time.realtimeSinceStartup;
return true;
}
#endregion
#region DuelFunctions
void CreateRequest(BasePlayer starter, BasePlayer opponent)
{
SendReply(starter, String.Format(createRequest, opponent.displayName));
SendReply(opponent, String.Format(receiveRequest, starter.displayName));
DuelPlayer dueller1 = starter.GetComponent<DuelPlayer>() ?? starter.gameObject.AddComponent<DuelPlayer>();
DuelPlayer dueller2 = opponent.GetComponent<DuelPlayer>() ?? opponent.gameObject.AddComponent<DuelPlayer>();
ActiveDuel activeDuel = starter.gameObject.AddComponent<ActiveDuel>();
activeDuel.player1 = dueller1;
activeDuel.player2 = dueller2;
createdDuels.Add(activeDuel);
}
void AcceptRequest(BasePlayer player)
{
Arena arena = null;
foreach (var duel in createdDuels)
{
if (duel.player2.player == player)
{
if (!canAcceptRequest(player) || !canAcceptRequest(duel.player1.player))
{
CancelRequest(player);
return;
}
duel.arena = FreeArena();
arena = duel.arena;
duel.isRequest = false;
duel.timeWhenTp = UnityEngine.Time.realtimeSinceStartup;
duel.player1.spawnPos = arena.player1pos;
duel.player2.spawnPos = arena.player2pos;
Debug($"Началась Дуэль {duel.player1.player.displayName} : {duel.player2.player.displayName} {arena.name} Активных: {busyArena.Count}");
toRemoveCorpse.Add(duel.player1.player.userID);
toRemoveCorpse.Add(duel.player2.player.userID);
duel.player1.PrepairToDuel();
duel.player2.PrepairToDuel();
Trade?.CallHook("RemovePending", duel.player1.player);
Trade?.CallHook("RemovePending", duel.player2.player);
break;
}
}
}
public void CancelRequest(BasePlayer player)
{
if (createdTeamDuels.Count > 0)
{
var duel = createdTeamDuels[0];
if (duel.owner == player && !duel.isStarted && !duel.allHere)
{
if (duel.teamblue.Count > 0)
foreach (var dueller in duel.teamblue)
{
dueller.Destroy();
}
if (duel.teamred.Count > 0)
foreach (var dueller in duel.teamred)
{
dueller.Destroy();
}
PrintToChat("Командная дуэль отменена создателем");
duel.Destroy();
return;
}
if (duel.requestPlayers.ContainsKey(player))
{
duel.requestPlayers.Remove(player);
player.ChatMessage("Вы покинули командную дуэль");
duel.owner.ChatMessage($"{player.displayName} отменил заявку на дуэль");
return;
}
var redplayer = duel.teamred.Find(x => x.player == player);
if (redplayer != null)
{
if (!redplayer.haveweapon && !duel.isStarted && !duel.allHere)
{
duel.teamred.Remove(redplayer);
redplayer.Destroy();
duel.owner.ChatMessage($"{player.displayName} покинул командную дуэль");
player.ChatMessage("Вы покинули командную дуэль");
return;
}
else
{
player.ChatMessage("Вы не можете покинуть начавшуюся дуэль");
return;
}
}
var blueplayer = duel.teamblue.Find(x => x.player == player);
if (blueplayer != null)
{
if (!blueplayer.haveweapon && !duel.isStarted && !duel.allHere)
{
duel.teamblue.Remove(blueplayer);
blueplayer.Destroy();
duel.owner.ChatMessage($"{player.displayName} покинул командную дуэль");
player.ChatMessage("Вы покинули командную дуэль");
return;
}
else
{
player.ChatMessage("Вы не можете покинуть начавшуюся дуэль");
return;
}
}
}
if (FindOpponent(player) != null)
{
var duel = FindDuelByPlayer(player);
if (duel != null)
{
if (duel.isRequest)
{
duel.RequestRemove();
return;
}
else
{
player.ChatMessage(cantCancelDuel);
return;
}
}
}
player.ChatMessage("Вы не участник дуэли");
}
static ActiveDuel FindDuelByPlayer(BasePlayer player)
{
foreach (var duel in createdDuels)
{
if (duel.player1.player == player)
{
return duel;
}
if (duel.player2.player == player)
{
return duel;
}
}
return null;
}
public void EndDuel(BasePlayer player, int reason, string UserId, string UserIdLoss)
{
DuelPlayer dueller = player?.GetComponent<DuelPlayer>();
if (dueller != null)
{
if (dueller.team != "")
{
if (reason == 6)
{
if (dueller.savedHome)
{
dueller.ReturnPlayer(reason);
}
else
{
dueller.Destroy();
}
return;
}
if (reason == 0 || reason == 4)
{
dueller.ReturnPlayer(reason);
}
return;
}
}
if (createdTeamDuels.Count > 0 && reason == 4)
{
if (createdTeamDuels[0].owner == player)
{
createdTeamDuels[0].RequestRemove();
return;
}
if (createdTeamDuels[0].requestPlayers.ContainsKey(player))
{
createdTeamDuels[0].requestPlayers.Remove(player);
createdTeamDuels[0].owner.ChatMessage($"[Дуэль] {player.displayName} вышел с сервера!");
return;
}
}
if (createdDuels.Count == 0) return;
DuelPlayer player1 = null;
DuelPlayer player2 = null;
foreach (var duel in createdDuels)
{
if (duel.player1.player == player)
{
player1 = duel.player1;
player2 = duel.player2;
break;
}
if (duel.player2.player == player)
{
player1 = duel.player1;
player2 = duel.player2;
break;
}
}
if (reason == 0)
{
if (player1 != null)
if (player1.player == player)
{
player1.guiEnabled = false;
player1.canMove = true;
player1.ReturnPlayer(0);
return;
}
if (player2 != null)
if (player2.player == player)
{
player2.guiEnabled = false;
player2.canMove = true;
player2.ReturnPlayer(0);
return;
}
}
if (reason == 7)
{
if (player1 != null)
if (player1.player == player)
{
player2.guiEnabled = false;
player2.canMove = true;
if (player2.induel)
player2.ReturnWithCooldown();
player2.induel = false;
return;
}
if (player2 != null)
if (player2.player == player)
{
player1.guiEnabled = false;
player1.canMove = true;
if (player1.induel)
player1.ReturnWithCooldown();
player1.induel = false;
return;
}
}
if (player1 != null)
{
player1.guiEnabled = false;
player1.canMove = true;
player1.ReturnPlayer(reason);
}
if (player2 != null)
{
player2.guiEnabled = false;
player2.canMove = true;
player2.ReturnPlayer(reason);
}
}
#endregion
#region TeamDuel
#region Class TeamDuel
class TeamDuel : MonoBehaviour
{
public List<DuelPlayer> teamblue = new List<DuelPlayer>();
public List<DuelPlayer> teamred = new List<DuelPlayer>();
public List<DuelPlayer> allPlayers = new List<DuelPlayer>();
public List<BasePlayer> statTeamBlue = new List<BasePlayer>();
public List<BasePlayer> statTeamRed = new List<BasePlayer>();
public Dictionary<BasePlayer, string> requestPlayers = new Dictionary<BasePlayer, string>();
public BasePlayer owner;
public Arena arena = null;
public bool isRequest = true;
public bool isStarted = false;
public bool needCheckStart;
public bool isActive = true;
public bool allHere;
public bool allReady;
public bool isPermDuel = false;
public bool randomWeaponsHasGiven = false;
public float guiTime;
public int playersAmount = -1;
public float startTime;
public float requestTime;
public float lastTimeMessage = 0f;
public List<Item> droppedWeapons = new List<Item>();
void Awake()
{
requestTime = UnityEngine.Time.realtimeSinceStartup;
allHere = false;
allReady = false;
}
public void CheckOnline()
{
int redCount = teamred.Count;
int blueCount = teamblue.Count;
List<string> offPlayers = new List<string>();
if (redCount > 0)
{
for (int i = 0; i < redCount; i++)
{
if (teamred[i] == null)
{
offPlayers.Add(teamred[i].player.displayName);
allPlayers.Remove(teamred[i]);
teamred.Remove(teamred[i]);
break;
}
}
}
if (blueCount > 0)
{
for (int i = 0; i < blueCount; i++)
{
if (teamblue[i] == null)
{
offPlayers.Add(teamblue[i].player.displayName);
allPlayers.Remove(teamblue[i]);
teamblue.Remove(teamblue[i]);
break;
}
}
}
redCount = teamred.Count;
blueCount = teamblue.Count;
int offPlayersCount = offPlayers.Count;
if (offPlayersCount > 0)
{
if (blueCount > 0)
{
for (int i = 0; i < blueCount; i++)
{
for (int j = 0; j < offPlayersCount; j++)
teamblue[i].player.ChatMessage(String.Format(teamPlayerDisconnect, offPlayers[j]));
}
}
if (redCount > 0)
{
for (int i = 0; i < redCount; i++)
{
for (int j = 0; j < offPlayersCount; j++)
teamred[i].player.ChatMessage(String.Format(teamPlayerDisconnect, offPlayers[j]));
}
}
}
}
void FixedUpdate()
{
if (isActive)
{
CheckOnline();
}
if (!isStarted && !allHere && teamblue.Count > 0 && teamred.Count > 0)
{
if ((teamblue.Count + teamred.Count) == (playersAmount * 2))
{
allHere = true;
int teamPlayersN = teamblue.Count;
for (int i = 0; i < teamPlayersN; i++)
{
var tmb = teamblue[i];
var tmr = teamred[i];
statTeamBlue.Add(tmb.player);
statTeamRed.Add(tmr.player);
allPlayers.Add(tmb);
allPlayers.Add(tmr);
}
Invoke("CheckDuellers", 5f);
needCheckStart = true;
}
}
if (needCheckStart)
{
if (isStarted && isActive)
{
if (teamblue.Count == 0)
{
isStarted = false;
isActive = false;
ConsoleNetwork.BroadcastToAllClients("chat.add", 0, teamWinRed);
int statPlayersN = statTeamRed.Count;
for (int i = 0; i < statPlayersN; i++)
{
db.playerStat[statTeamRed[i].userID].teamwins++;
db.playerStat[statTeamBlue[i].userID].teamloss++;
}
Invoke("EndTeamDuelWithWinners", 5f);
return;
}
if (teamred.Count == 0)
{
isStarted = false;
isActive = false;
ConsoleNetwork.BroadcastToAllClients("chat.add", 0, teamWinBlue);
int statPlayersN = statTeamRed.Count;