-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathAutoRefMatch.java
More file actions
3705 lines (3062 loc) · 108 KB
/
AutoRefMatch.java
File metadata and controls
3705 lines (3062 loc) · 108 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
package org.mctourney.autoreferee;
import java.awt.image.RenderedImage;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Difficulty;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Ambient;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Item;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.material.Attachable;
import org.bukkit.material.Button;
import org.bukkit.material.Lever;
import org.bukkit.material.MaterialData;
import org.bukkit.material.PressurePlate;
import org.bukkit.material.PressureSensor;
import org.bukkit.material.Redstone;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.JDOMParseException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mctourney.autoreferee.event.match.MatchCompleteEvent;
import org.mctourney.autoreferee.event.match.MatchStartEvent;
import org.mctourney.autoreferee.event.match.MatchTranscriptEvent;
import org.mctourney.autoreferee.event.match.MatchUnloadEvent;
import org.mctourney.autoreferee.event.match.MatchUploadStatsEvent;
import org.mctourney.autoreferee.event.player.PlayerMatchJoinEvent;
import org.mctourney.autoreferee.event.player.PlayerMatchLeaveEvent;
import org.mctourney.autoreferee.event.player.PlayerTeamJoinEvent;
import org.mctourney.autoreferee.goals.AutoRefGoal;
import org.mctourney.autoreferee.goals.TimeGoal;
import org.mctourney.autoreferee.goals.scoreboard.AutoRefObjective;
import org.mctourney.autoreferee.listeners.GoalsInventorySnapshot;
import org.mctourney.autoreferee.listeners.SpectatorListener;
import org.mctourney.autoreferee.listeners.ZoneListener;
import org.mctourney.autoreferee.regions.AutoRefRegion;
import org.mctourney.autoreferee.regions.CuboidRegion;
import org.mctourney.autoreferee.regions.RegionGraph;
import org.mctourney.autoreferee.util.ArmorPoints;
import org.mctourney.autoreferee.util.BlockData;
import org.mctourney.autoreferee.util.BookUtil;
import org.mctourney.autoreferee.util.LocationUtil;
import org.mctourney.autoreferee.util.MapImageGenerator;
import org.mctourney.autoreferee.util.Metadatable;
import org.mctourney.autoreferee.util.PlayerKit;
import org.mctourney.autoreferee.util.PlayerUtil;
import org.mctourney.autoreferee.util.QueryUtil;
import org.mctourney.autoreferee.util.ReportGenerator;
import org.mctourney.autoreferee.util.SportBukkitUtil;
import org.mctourney.autoreferee.util.TeleportationUtil;
/**
* Represents a game world controlled by AutoReferee.
*
* @author authorblues
*/
public class AutoRefMatch implements Metadatable
{
// modify the internal NMS scoreboard instance with a custom scoreboard
private static final boolean REPLACE_INTERNAL_SCOREBOARD = false;
// online map list
private static String MAPREPO = "http://autoreferee.s3.amazonaws.com/";
/**
* Get the base url for the map repository
* @return url of map repository
*/
public static String getMapRepo()
{ return MAPREPO; }
/**
* Sets a new map repository for the plugin to download maps
* @param url url of new map repository to use
*/
public static void changeMapRepo(String url)
{ MAPREPO = url + "/"; }
// set this to false to not give match info books to players
public static boolean giveMatchInfoBooks = true;
static
{
File matchSummaryDirectory;
// determine the location of the match-summary directory
FileConfiguration config = AutoReferee.getInstance().getConfig();
if (config.isString("local-storage.match-summary.directory"))
matchSummaryDirectory = new File(config.getString("local-storage.match-summary.directory"));
else matchSummaryDirectory = new File(AutoReferee.getInstance().getDataFolder(), "summary");
// if the folder doesnt exist, create it...
if (!matchSummaryDirectory.exists()) matchSummaryDirectory.mkdir();
}
protected Map<String, Object> metadata = Maps.newHashMap();
public void addMetadata(String key, Object value)
{ this.metadata.put(key, value); }
public Object getMetadata(String key)
{ return this.metadata.get(key); }
public boolean hasMetadata(String key)
{ return this.metadata.containsKey(key); }
public Object removeMetadata(String key)
{ return this.metadata.remove(key); }
public void clearMetadata()
{ this.metadata.clear(); }
public enum AccessType
{ PRIVATE, PUBLIC }
public AccessType access = AccessType.PRIVATE;
protected boolean currentlyTied = false;
// world this match is taking place on
private World primaryWorld;
private AutoRefRegion worldSpawn = null;
private AutoRefRegion specSpawn = null;
private void setPrimaryWorld(World w)
{
primaryWorld = w;
worldConfigFile = new File(w.getWorldFolder(), AutoReferee.CFG_FILENAME);
setWorldSpawn(primaryWorld.getSpawnLocation());
}
public void setWorldSpawn(Location loc)
{
while (!TeleportationUtil.isBlockPassable(loc.getWorld().getBlockAt(loc))) loc = loc.add(0, 1, 0);
worldSpawn = new org.mctourney.autoreferee.regions.PointRegion(loc);
loc.getWorld().setSpawnLocation(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
public void setSpectatorSpawn(Location loc)
{
while (!TeleportationUtil.isBlockPassable(loc.getWorld().getBlockAt(loc))) loc = loc.add(0, 1, 0);
specSpawn = new org.mctourney.autoreferee.regions.PointRegion(loc);
}
public boolean isPracticeMode()
{
if (!this.getCurrentState().inProgress()) return false;
int existingteams = 0;
for (AutoRefTeam team : this.getTeams())
if (!team.isEmptyTeam()) ++existingteams;
return existingteams < 2;
}
public boolean willBePracticeMode()
{
int existingteams = 0;
for (AutoRefTeam team : this.getTeams())
if (!team.isEmptyTeam()) ++existingteams;
return existingteams < 2;
}
protected boolean previewMode = false;
public void setPreviewMode(boolean b)
{ this.previewMode = b; }
public boolean isPreviewMode()
{ return this.previewMode; }
/**
* Gets the world associated with this match.
*
* @return world
*/
public World getWorld()
{ return primaryWorld; }
@Override public int hashCode()
{ return getWorld().hashCode(); }
@Override public String toString()
{
return String.format("%s[%s, w=%s]", this.getClass().getSimpleName(),
this.mapName, this.getWorld().getName());
}
/**
* Gets the global spawn location for this match.
*
* @return global spawn location
*/
public Location getWorldSpawn()
{ return worldSpawn.getLocation(); }
/**
* Gets the global spawn location for this match.
*
* @return global spawn location
*/
public Location getSpectatorSpawn()
{ return specSpawn != null ? specSpawn.getLocation() : getWorldSpawn(); }
private boolean tmp;
public AutoRefMatch temporary()
{ this.tmp = true; return this; }
public boolean isTemporaryWorld()
{ return tmp; }
private long startClock = 0L;
protected boolean lockTime = false;
/**
* Gets the time to set the world to at the start of the match.
*
* @return world time in ticks to be set at start of the match
*/
public long getStartClock()
{ return startClock; }
/**
* Represents the status of a match.
*
* @author authorblues
*/
public enum MatchStatus
{
/**
* No match for this world.
*/
NONE,
/**
* Waiting for players to join.
*/
WAITING(5*60*1000L),
/**
* Players joined, waiting for match start.
*/
READY(5*60*1000L),
/**
* Match in progress.
*/
PLAYING(30*60*1000L),
/**
* Match completed.
*/
COMPLETED(5*60*1000L);
public long inactiveMillis;
MatchStatus()
{ this(Long.MAX_VALUE); }
MatchStatus(long ms)
{ this.inactiveMillis = ms; }
/**
* Checks if the match has not yet started.
*
* @return true if match has not started, otherwise false
*/
public boolean isBeforeMatch()
{ return this.ordinal() < PLAYING.ordinal() && this != NONE; }
/**
* Checks if the match has completed.
*
* @return true if match is completed, otherwise false
*/
public boolean isAfterMatch()
{ return this.ordinal() > PLAYING.ordinal() && this != NONE; }
/**
* Checks if match is in progress.
*
* @return true if match is in progress, otherwise false
*/
public boolean inProgress()
{ return this == PLAYING; }
}
// status of the match
private MatchStatus currentState = MatchStatus.NONE;
/**
* Gets the current status of this match.
*
* @return match status
*/
public MatchStatus getCurrentState()
{ return currentState; }
/**
* Sets the current status of this match.
*
* @param status new match status
*/
public void setCurrentState(MatchStatus status)
{
this.currentState = status;
if (!status.isBeforeMatch()) this.setupSpectators();
}
// custom scoreboard
protected final Scoreboard scoreboard;
protected final Scoreboard infoboard;
protected Objective infoboardObjective;
protected List<Objective> allInfoObjectives;
public Scoreboard getScoreboard()
{ return scoreboard; }
Scoreboard getInfoboard()
{ return infoboard; }
// teams participating in the match
protected Set<AutoRefTeam> teams = Sets.newHashSet();
/**
* Gets the teams participating in this match.
*
* @return set of teams
*/
public Set<AutoRefTeam> getTeams()
{ return teams; }
public String getTeamList()
{
Set<String> tlist = Sets.newHashSet();
for (AutoRefTeam team : getTeams())
tlist.add(team.getDisplayName());
return StringUtils.join(tlist, ", ");
}
private AutoRefTeam winningTeam = null;
/**
* Gets the team that won this match.
*
* @return team that won the match if it is over, otherwise null
*/
public AutoRefTeam getWinningTeam()
{ return winningTeam; }
/**
* Sets the team that won this match.
*/
public void setWinningTeam(AutoRefTeam team)
{ winningTeam = team; }
protected Map<String, PlayerKit> kits;
public PlayerKit getKit(String name)
{ return kits.get(name); }
// region defined as the "start" region (safe zone)
private Set<AutoRefRegion> startRegions = Sets.newHashSet();
/**
* Gets the region designated as the start platform. This region should contain the
* world spawn location. Players in this region are immune to damage from other players,
* and mobs will not spawn in this region.
*
* @return start region
*/
public Set<AutoRefRegion> getStartRegions()
{ return startRegions; }
public void addStartRegion(AutoRefRegion reg)
{ this.startRegions.add(reg); }
private Set<AutoRefRegion.Flag> startRegionFlags = Sets.newHashSet
( AutoRefRegion.Flag.NO_BUILD
, AutoRefRegion.Flag.SAFE
, AutoRefRegion.Flag.NO_EXPLOSIONS
);
public Set<AutoRefRegion.Flag> getStartRegionFlags()
{ return Collections.unmodifiableSet(startRegionFlags); }
public double distanceToStartRegion(Location loc)
{
double dist = Double.MAX_VALUE;
for (AutoRefRegion reg : startRegions)
{
double d = reg.distanceToRegion(loc);
if (d < dist) dist = d;
}
return dist;
}
public CuboidRegion getMapCuboid()
{
CuboidRegion cube = null;
for (AutoRefRegion reg : getStartRegions())
cube = AutoRefRegion.combine(cube, reg);
for (AutoRefTeam team : getTeams())
for (AutoRefRegion reg : team.getRegions())
cube = AutoRefRegion.combine(cube, reg);
return cube;
}
// name of the match
private String matchName = null;
/**
* Sets the custom name for this match.
*
* @param name custom match name
*/
public void setMatchName(String name)
{ matchName = name; }
/**
* Gets the name of this match.
*
* @return match name
*/
public String getMatchName()
{
// if we have a specific match name...
if (matchName != null) return matchName;
// generate a date string
String date = new SimpleDateFormat("dd MMM yyyy").format(new Date());
// if the map is named, return map name as a placeholder
if (mapName != null) return mapName + ": " + date;
// otherwise, just return the date
return date;
}
// configuration information for the world
protected File worldConfigFile;
protected Element worldConfig;
private boolean saveConfig = true;
// basic variables loaded from file
protected String mapName = null;
protected Collection<String> mapAuthors = null;
/**
* Gets the name of the map for this match.
*
* @return map name
*/
public String getMapName()
{ return mapName; }
protected String versionString = "1.0";
/**
* Gets the version number of the map for this match.
*
* @return version number
*/
public String getMapVersion()
{ return versionString; }
/**
* Gets the shorthand version string of the map for this match. This string will have the format
* of "MapName-vX.Y"
*
* @return version string
*/
public String getVersionString()
{ return String.format("%s-v%s", normalizeMapName(this.getMapName()), this.getMapVersion()); }
public AutoRefMap getMap()
{ return AutoRefMap.getMap(mapName); }
/**
* Gets the creators of the map for this match.
*
* @return string list of names
*/
public String getAuthorList()
{
if (mapAuthors != null && mapAuthors.size() != 0)
return StringUtils.join(mapAuthors, ", ");
return "??";
}
private long startTime = 0;
public long getStartTime()
{ return startTime; }
public void setStartTime(long time)
{ this.startTime = time; }
/**
* Gets the number of seconds elapsed in this match.
*
* @return current elapsed seconds if match in progress, otherwise 0L
*/
public long recordedTime = 0L;
public long getElapsedSeconds()
{
if (!getCurrentState().inProgress()) return recordedTime;
return (ManagementFactory.getRuntimeMXBean().getUptime() - getStartTime()) / 1000L;
}
private long timeLimit = 0L;
/**
* Gets the match time limit in seconds.
*
* @return time limit in seconds
*/
public long getTimeLimit()
{ return timeLimit; }
/**
* Checks if this match has a set time limit.
*
* @return true if a time limit is set, otherwise false
*/
public boolean hasTimeLimit()
{ return timeLimit > 0L; }
/**
* Gets the number of seconds remaining in this match.
*
* @return time remaining in seconds
*/
public long getTimeRemaining()
{ return timeLimit - getElapsedSeconds(); }
/**
* Sets match time limit in seconds.
*
* @param limit new time limit in seconds
*/
public void setTimeLimit(long limit)
{ this.timeLimit = limit; }
/**
* Gets current match time, default value separator (colon).
*
* @return current match timestamp
*/
public String getTimestamp()
{ return getTimestamp(":"); }
/**
* Gets current match time, with value separator.
*
* @param sep time value separator
* @return current match timestamp
*/
public String getTimestamp(String sep)
{
long timestamp = this.getElapsedSeconds();
return String.format("%02d%s%02d%s%02d", timestamp/3600L,
sep, (timestamp/60L)%60L, sep, timestamp%60L);
}
// task that starts the match
protected CountdownTask matchStarter = null;
// mechanisms to open the starting gates
protected Set<StartMechanism> startMechanisms;
// protected entities - only protected from "butchering"
private Set<UUID> protectedEntities;
public boolean isProtected(UUID uuid)
{ return protectedEntities.contains(uuid); }
public void protect(UUID uuid)
{ protectedEntities.add(uuid); }
public void unprotect(UUID uuid)
{ protectedEntities.remove(uuid); }
public void toggleProtection(UUID uuid)
{ if (isProtected(uuid)) unprotect(uuid); else protect(uuid); }
protected boolean playersBecomeSpectators = true;
protected boolean allowFriendlyFire = true;
/**
* Checks if friendly fire is allowed in this match.
*
* @return true if friendly fire is allowed, otherwise false
*/
public boolean allowFriendlyFire()
{ return allowFriendlyFire; }
/**
* Sets whether friendly fire is allowed in this match.
*/
public void setFriendlyFire(boolean b)
{ this.allowFriendlyFire = b; }
// provided by configuration file
protected static boolean allowTies = false;
/**
* Checks if ties are allowed on this server.
*
* @return true if ties are allowed, otherwise false
*/
public static boolean areTiesAllowed()
{ return allowTies; }
/**
* Sets whether ties are allowed on this server.
*/
public static void setAllowTies(boolean b)
{ AutoRefMatch.allowTies = b; }
// list of items players may not craft
protected Set<BlockData> prohibitCraft = Sets.newHashSet();
// range of inexact placement
protected int inexactRange = 2;
/**
* Gets the distance an objective may be placed from its target location.
*
* @return range of inexact objective placement
*/
public int getInexactRange()
{ return inexactRange; }
// transcript of every event in the match
protected List<TranscriptEvent> transcript;
private boolean refereeReady = false;
/**
* Checks if the referees are ready for the match to start.
*
* @return true if referees are ready or there are no referees, otherwise false
*/
public boolean isRefereeReady()
{ return getReferees().size() == 0 || refereeReady; }
/**
* Sets whether the referees are ready for the match to start.
*/
public void setRefereeReady(boolean r)
{ refereeReady = r; }
private ReportGenerator matchReportGenerator = new ReportGenerator();
public void saveMapImage()
{
try
{
RenderedImage mapImage = getMapImage();
ImageIO.write(mapImage, "png", new File(getWorld().getWorldFolder(), "map.png"));
}
catch (IOException e) { e.printStackTrace(); }
}
public RenderedImage getMapImage() throws IOException
{
CuboidRegion cube = getMapCuboid();
if (cube == null) throw new IOException("No start regions defined.");
Location min = cube.getMinimumPoint(),
max = cube.getMaximumPoint();
return MapImageGenerator.generateFromWorld(getWorld(),
min.getBlockX(), max.getBlockX(), min.getBlockZ(), max.getBlockZ());
}
protected GameMode gamemode;
// number of seconds for each phase
public static final int READY_SECONDS = 15;
public static final int COMPLETED_SECONDS = 180;
private int customReadyDelay = -1;
/**
* Gets number of seconds between start of countdown and match starting.
*
* @return number of seconds for match countdown
*/
public int getReadyDelay()
{
if (customReadyDelay >= 0) return customReadyDelay;
return AutoReferee.getInstance().getConfig().getInt(
"delay-seconds.ready", AutoRefMatch.READY_SECONDS);
}
/**
* Sets number of seconds between start of countdown and match starting.
*/
public void setReadyDelay(int delay)
{ this.customReadyDelay = delay; }
public void notify(Location loc, String message)
{
// give spectators a location to warp to (null is acceptable)
this.setLastNotificationLocation(loc);
// send a notification message
if (message.trim().isEmpty()) message = "A notification has been sent. Type /artp to teleport.";
String m = ChatColor.DARK_GRAY + "[N] " + message;
for (Player pl : this.getReferees(false)) pl.sendMessage(m);
}
private Location lastNotificationLocation = null;
public Location getLastNotificationLocation()
{ return lastNotificationLocation; }
/**
* Sets a notification location for referees and streamers. This location should be the
* exact location of the event. The teleportation suite will find a suitable vantage point
* to observe the event.
*
* @param loc notification location
*/
public void setLastNotificationLocation(Location loc)
{ lastNotificationLocation = loc; }
private Location lastDeathLocation = null;
public Location getLastDeathLocation()
{ return lastDeathLocation; }
public void setLastDeathLocation(Location loc)
{
lastDeathLocation = loc;
setLastNotificationLocation(loc);
}
private Location lastLogoutLocation = null;
public Location getLastLogoutLocation()
{ return lastLogoutLocation; }
public void setLastLogoutLocation(Location loc)
{
lastLogoutLocation = loc;
setLastNotificationLocation(loc);
}
private Location lastTeleportLocation = null;
public Location getLastTeleportLocation()
{ return lastTeleportLocation; }
public void setLastTeleportLocation(Location loc)
{
lastTeleportLocation = loc;
setLastNotificationLocation(loc);
}
private Location lastObjectiveLocation = null;
public Location getLastObjectiveLocation()
{ return lastObjectiveLocation; }
public void setLastObjectiveLocation(Location loc)
{
lastObjectiveLocation = loc;
setLastNotificationLocation(loc);
}
public class BedUpdateTask extends BukkitRunnable
{
private Map<AutoRefPlayer, Boolean> hasBed = Maps.newHashMap();
private String breakerName, breakAction = "broken";
private AutoRefPlayer breaker;
public BedUpdateTask(AutoRefPlayer breaker)
{ this(breaker.getDisplayName()); this.breaker = breaker; }
public BedUpdateTask(Entity ent)
{
AutoReferee plugin = AutoReferee.getInstance();
switch (ent.getType())
{
case CREEPER: breakerName = "Creeper"; break;
case LIGHTNING: breakerName = "Lightning"; break;
case WITHER_SKULL: breakerName = "Wither Skull"; break;
case WITHER: breakerName = "Wither"; break;
case ENDER_CRYSTAL: breakerName = "Ender Crystal"; break;
case ENDER_DRAGON: breakerName = "Ender Dragon"; break;
case FIREBALL:
case SMALL_FIREBALL:
breakerName = "Fireball"; break;
case PRIMED_TNT:
AutoRefPlayer tntOwner = plugin.getTNTOwner(ent);
if (tntOwner == null) breakerName = "TNT";
else breakerName = String.format("%s's TNT", tntOwner.getDisplayName());
break;
}
for (AutoRefPlayer apl : getPlayers())
hasBed.put(apl, apl.hasBed());
breakAction = "blown up";
}
public BedUpdateTask(String breakerName)
{
this.breakerName = breakerName;
for (AutoRefPlayer apl : getPlayers())
hasBed.put(apl, apl.hasBed());
breakAction = "broken";
}
public void run()
{
Set<AutoRefPlayer> lostBed = Sets.newHashSet();
String bedBreakNotification;
for (AutoRefPlayer apl : getPlayers())
if (hasBed.get(apl) != apl.hasBed()) lostBed.add(apl);
// if no one's bed changed, quit here
if (lostBed.isEmpty()) return;
// don't print or do anything if the bed's owner breaks it himself
if (breaker != null && lostBed.contains(breaker)) return;
if (lostBed.size() == 1)
bedBreakNotification = String.format("%s's bed has been %s by %s.",
((AutoRefPlayer) lostBed.toArray()[0]).getDisplayName(), breakAction, breakerName);
else
{
// get the team that owns this bed (null if owned by more than one team)
AutoRefTeam teamOwner = ((AutoRefPlayer) lostBed.toArray()[0]).getTeam();
for (AutoRefPlayer apl : lostBed) if (apl.getTeam() != teamOwner) teamOwner = null;
bedBreakNotification = teamOwner != null
? String.format("%s's bed has been %s by %s.", teamOwner.getDisplayName(), breakAction, breakerName)
: String.format("%s has %s a bed.", breakerName, breakAction);
}
for (Player ref : getReferees(false))
ref.sendMessage(bedBreakNotification);
}
}
private class PlayerCountTask extends BukkitRunnable
{
private long lastOccupiedTime = 0;
public PlayerCountTask()
{ lastOccupiedTime = ManagementFactory.getRuntimeMXBean().getUptime(); }
public void run()
{
long tick = ManagementFactory.getRuntimeMXBean().getUptime();
// if there are people in this world/match, reset last-occupied
if (getUserCount() != 0) lastOccupiedTime = tick;
// if this world has been inactive for long enough, just unload it
if (tick - lastOccupiedTime >= getCurrentState().inactiveMillis)
destroy(MatchUnloadEvent.Reason.EMPTY);
}
}
PlayerCountTask countTask = null;
public AutoRefMatch(World world, boolean tmp, MatchStatus state)
{ this(world, tmp); setCurrentState(state); }
@SuppressWarnings("deprecation")
public AutoRefMatch(World world, boolean tmp)
{
setPrimaryWorld(world);
world.setKeepSpawnInMemory(true);
// is this world a temporary world?
this.tmp = tmp;
// should eliminated players become spectators?
this.playersBecomeSpectators = AutoReferee.getInstance().getConfig()
.getBoolean("players-become-spectators", true);
// setup custom scoreboard
scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
infoboard = Bukkit.getScoreboardManager().getNewScoreboard();
if (AutoRefMatch.REPLACE_INTERNAL_SCOREBOARD) try
{
Method wHandle = world.getClass().getDeclaredMethod("getHandle");
Object nmsWorld = wHandle.invoke(world);
Method sHandle = scoreboard.getClass().getDeclaredMethod("getHandle");
Object nmsScoreboard = sHandle.invoke(scoreboard);
Field fScoreboard = nmsWorld.getClass().getField("scoreboard");
fScoreboard.setAccessible(true);
fScoreboard.set(nmsWorld, nmsScoreboard);
}
catch (Exception e)
{
AutoReferee.log("A problem occured whilst modifying NMS scoreboard internal values.");
AutoReferee.log("Are you sure you are using a CraftBukkit variant?");
AutoReferee.log("Please file a bug report, as this is a somewhat serious error.");
e.printStackTrace();
}
messageReferees("match", getWorld().getName(), "init");
loadWorldConfiguration();
this.createRegionGraphs();
try {
this.loadRegionJSON();
} catch (FileNotFoundException | ClassCastException e) {
AutoReferee.log("Failed to load " + REGION_CFG_FILENAME);
e.printStackTrace();
}
/*if(AutoReferee.getInstance().isExperimentalMode()) { // experimental feature
this.initRegionGraphs();
graphTask =
new BukkitRunnable() {
@Override
public void run() {
computeRegionGraphs();
graphTask = null;
}
}.runTaskAsynchronously(AutoReferee.getInstance());
}*/
messageReferees("match", getWorld().getName(), "map", getMapName());