-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathAutoRefTeam.java
More file actions
1066 lines (871 loc) · 30.6 KB
/
AutoRefTeam.java
File metadata and controls
1066 lines (871 loc) · 30.6 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.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.stream.Collectors;
import com.google.common.collect.Maps;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import org.jdom2.Element;
import org.mctourney.autoreferee.event.player.PlayerTeamJoinEvent;
import org.mctourney.autoreferee.event.player.PlayerTeamLeaveEvent;
import org.mctourney.autoreferee.event.team.ObjectiveUpdateEvent;
import org.mctourney.autoreferee.goals.AutoRefGoal;
import org.mctourney.autoreferee.goals.BlockGoal;
import org.mctourney.autoreferee.goals.scoreboard.AutoRefObjective;
import org.mctourney.autoreferee.listeners.GoalsInventorySnapshot;
import org.mctourney.autoreferee.listeners.ZoneListener;
import org.mctourney.autoreferee.regions.AutoRefRegion;
import org.mctourney.autoreferee.regions.AutoRefRegion.Flag;
import org.mctourney.autoreferee.regions.RegionGraph;
import org.mctourney.autoreferee.util.BlockData;
import org.mctourney.autoreferee.util.Metadatable;
import org.mctourney.autoreferee.util.PlayerKit;
import org.mctourney.autoreferee.util.PlayerUtil;
import org.mctourney.autoreferee.util.Vec3;
import org.apache.commons.lang.StringUtils;
import com.google.common.collect.Sets;
/**
* Represents a collection of players in a match.
*
* @author authorblues
*/
public class AutoRefTeam implements Metadatable, Comparable<AutoRefTeam>
{
public class JSONTeamData
{
public String defaultname;
public String customname;
public Map<String, AutoRefPlayer.JSONPlayerData> players;
// TODO goal data?
}
// reference to the match
protected AutoRefMatch match = null;
/**
* Gets this team's match.
*
* @return match object
*/
public AutoRefMatch getMatch()
{ return match; }
org.bukkit.scoreboard.Team scoreboardTeam;
org.bukkit.scoreboard.Team infoboardTeam;
// player information
protected Set<AutoRefPlayer> players = Sets.newHashSet();
private Set<AutoRefPlayer> playersCache = Sets.newHashSet();
private int playerlives = -1;
public String toString()
{ return this.getClass().getSimpleName() + "[" + this.getName() + "]"; }
public boolean equals(Object o)
{
return this.getClass().isInstance(o)
&& this.getMatch().equals(((AutoRefTeam) o).getMatch())
&& this.name.equals(((AutoRefTeam) o).name);
}
public int hashCode()
{ return this.name.hashCode() ^ (17 * this.getMatch().hashCode()); }
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(); }
/**
* Gets the members of this team.
*
* @return collection of players
*/
public Set<AutoRefPlayer> getPlayers()
{ return players; }
public Set<AutoRefPlayer> getCachedPlayers()
{ return playersCache; }
protected String getPlayerList()
{
Set<String> plist = Sets.newHashSet();
for (AutoRefPlayer apl : getPlayers())
plist.add(apl.getName());
if (plist.size() == 0) return "{empty}";
return StringUtils.join(plist, ", ");
}
private Set<String> expectedPlayers = Sets.newHashSet();
/**
* Adds a player to the list of expected players for this team.
*/
public void addExpectedPlayer(OfflinePlayer opl)
{ addExpectedPlayer(opl.getName()); }
/**
* Adds a player to the list of expected players for this team by name.
*/
public void addExpectedPlayer(String name)
{ expectedPlayers.add(name.toLowerCase()); }
/**
* Gets the players expected to join this team.
*
* @return collection of players
*/
public Set<String> getExpectedPlayers()
{ return expectedPlayers; }
// team's name, may or may not be color-related
private String name = null;
private String customName = null;
protected String scoreboardTeamName = null;
/**
* Gets the default name of the team.
*/
public String getDefaultName()
{ return name; }
/**
* Gets the name of the team.
*/
public String getName()
{
if (customName != null) return customName;
return this.getDefaultName();
}
/**
* Sets the name of the team.
*
* @param name new team name
*/
public void setName(String name)
{
// send name change event before we actually change the name
match.messageReferees("team", getName(), "name", name);
String oldName = getDisplayName();
customName = name;
if (!oldName.equals(getDisplayName()))
match.broadcast(oldName + " is now known as " + getDisplayName());
scoreboardTeam.setDisplayName(name);
// update objectives to propagate name changes
this.updateObjectives();
}
public String getScoreboardTeamName()
{ return scoreboardTeamName == null ? ("ar#" + name) : scoreboardTeamName; }
/**
* Gets the colored name of the team.
*/
public String getDisplayName()
{ return color + getName() + ChatColor.RESET; }
// color to use for members of this team
private ChatColor color = ChatColor.WHITE;
/**
* Gets the color associated with this team.
*/
public ChatColor getColor()
{ return color; }
/**
* Sets the color associated with this team.
*/
public void setColor(ChatColor color)
{ this.color = color; }
// maximum size of a team
protected Integer maxsize = null;
protected Integer minsize = null;
public int getMaxSize()
{ return maxsize == null ? 4 : maxsize; }
public int getMinSize()
{ return minsize == null ? (3 * getMaxSize() / 4) : minsize; }
// is this team ready to play?
private boolean ready = false;
/**
* Checks if this team is ready for the match to begin.
*
* @return true if team is ready, otherwise false
*/
public boolean isReady()
{ return ready || this.isEmptyTeam(); }
/**
* Sets whether this team is ready for the match to begin.
*/
public void setReady(boolean ready)
{
if (ready == this.ready) return;
this.ready = ready;
for (Player pl : getMatch().getWorld().getPlayers())
pl.sendMessage(getDisplayName() + " is now marked as " +
ChatColor.DARK_GRAY + (this.ready ? "READY" : "NOT READY"));
if (!this.ready) getMatch().cancelCountdown();
}
/**
* Checks whether this team is empty. Takes expected players into account.
*
* @return true if team is empty, otherwise false
*/
public boolean isEmptyTeam()
{ return getPlayers().size() == 0 && getExpectedPlayers().size() == 0; }
private Location lastObjectiveLocation = null;
/**
* Gets location of this team's last objective event.
*/
public Location getLastObjectiveLocation()
{ return lastObjectiveLocation; }
public void setLastObjectiveLocation(Location loc)
{
lastObjectiveLocation = loc;
getMatch().setLastObjectiveLocation(loc);
}
private static final Vector HALF_BLOCK_VECTOR = new Vector(0.5, 0.5, 0.5);
/**
* Gets location of this team's victory monument. Victory monument location
* is synthesized based on objective target locations.
*/
public Location getVictoryMonumentLocation()
{
Vector vmin = null, vmax = null;
for (BlockGoal goal : this.getTeamGoals(BlockGoal.class))
{
Vector v = goal.getTarget().toVector().add(HALF_BLOCK_VECTOR);
vmin = vmin == null ? v : Vector.getMinimum(vmin, v);
vmax = vmax == null ? v : Vector.getMaximum(vmax, v);
}
// if we didn't find any block goals, no victory monument
if (vmin == null || vmax == null) return null;
World w = getMatch().getWorld();
return vmin.getMidpoint(vmax).toLocation(w);
}
/**
* Gets all regions owned by this team.
*
* @return collection of regions
*/
public Set<AutoRefRegion> getRegions()
{ return match.getRegions(this); }
/**
* Returns whether a particular Location
* is in team's lane or not
* @author char
*
* @param loc
* @return
*/
public boolean containsLoc(Location loc)
{ return this.getRegions().stream().anyMatch(reg -> reg.contains(loc)); }
public boolean addRegion(AutoRefRegion reg)
{
for (AutoRefRegion ereg : match.getRegions())
if (reg.equals(ereg)) { ereg.addOwners(this); return true; }
reg.addOwners(this);
match.getRegions().add(reg);
return true;
}
// location of custom spawn
private Set<AutoRefRegion> spawnRegions = Sets.newHashSet();
private static Random random = new Random();
/**
* Clears this team's spawn locations.
*/
public void clearSpawnRegions()
{ this.spawnRegions = Sets.newHashSet(); }
/**
* Adds to this team's spawn locations.
*/
public void addSpawnRegion(AutoRefRegion reg)
{ this.spawnRegions.add(reg); }
/**
* Adds to this team's spawn locations.
*/
public void addSpawnRegion(Location loc)
{ this.addSpawnRegion(new org.mctourney.autoreferee.regions.PointRegion(loc)); }
/**
* Gets a valid spawn location for this team.
*/
public Location getSpawnLocation()
{
if (spawnRegions == null || spawnRegions.isEmpty())
return match.getWorldSpawn();
AutoRefRegion[] regs = spawnRegions.toArray(new AutoRefRegion[0]);
return regs[random.nextInt(spawnRegions.size())].getLocation();
}
private RegionGraph graph;
private Set<Set<Vec3>> restrictedRegions;
public RegionGraph getRegGraph() { return this.graph; }
public void setRestrictionRegions(Set<Set<Vec3>> regions)
{ this.restrictedRegions = regions; }
public boolean regGraphLoaded() { return this.getRegGraph().loaded(); }
public void initRegionGraph() {
createRegionGraph();
graph.computeGraph();
}
public void createRegionGraph() {
// this is an experimental feature
if(!AutoReferee.getInstance().isExperimentalMode()) return;
if(this.getMatch() == null) return;
World w = this.getMatch().getWorld();
if(w == null) return;
if(this.getRegions() == null) return;
graph = new RegionGraph(w, this.getRegions(), AutoReferee.getInstance().getLogger(), this)
.regions(this.getRegions());
/*.setDungeonOpenings( this.getRegions().stream()
.filter(r -> r.getFlags().contains(Flag.DUNGEON_BOUNDARY))
.collect(Collectors.toSet()));*/
}
// safe from async thread
public void computeRegionGraph() {
// this is an expiremental feature
if(!AutoReferee.getInstance().isExperimentalMode()) return;
if(this.getRegions() == null) return;
RegionGraph graph = this.getRegGraph();
if(graph == null) return;
if(this.getMatch() == null) return;
World w = this.getMatch().getWorld();
if(w == null) return;
graph.findConnectedRegions();
}
public Set<Location> unrestrictedPts() {
if(this.getRegions() == null) return null;
return this.getRegions().stream()
.filter(reg -> reg.getFlags().contains(Flag.NON_RESTRICTED))
.map(reg -> reg.getBoundingCuboid().getMinimumPoint().getBlock().getLocation())
.collect(Collectors.toSet());
}
/*public Set<AutoRefRegion> dungeonOpenings() {
if(this.getRegions() == null) return null;
return this.regions().stream()
.filter(r -> r.getFlags().contains(Flag.DUNGEON_BOUNDARY))
.collect(Collectors.toSet());
}*/
public Set<Vec3> restrictedRegion(Location l) {
if(this.getRegGraph() == null) return null;
if(this.restrictedRegions != null) {
return this.restrictedRegions.stream()
.filter(reg -> reg.contains( this.getRegGraph().vec(l) ))
.findAny().orElse(null);
}
if(!this.getRegGraph().loaded()) return null;
if(this.getRegGraph().connectedRegions().isEmpty()) return null;
return this.getRegGraph().connectedRegions().stream()
.filter(reg -> reg.contains( this.getRegGraph().vec(l) ))
.findAny().orElse(null);
}
public boolean isRestrictedLoc(Location l) {
boolean def = false;
if(this.getRegGraph() == null) return def;
if(this.restrictedRegions != null) {
return this.getRegGraph()
.isRestricted(l, this.restrictedRegions, this.getRegions());
}
if(!this.getRegGraph().loaded()) return def;
if(this.getRegGraph().connectedRegions().isEmpty()) return def;
return this.getRegGraph().isInRestrictedArea(l, this.unrestrictedPts());
}
private Set<AutoRefGoal> goals = Sets.newHashSet();
/**
* Get this team's win conditions.
*
* @return collection of win conditions
*/
public Set<AutoRefGoal> getTeamGoals()
{ return Collections.unmodifiableSet(goals); }
/**
* Get this team's win conditions by type.
*
* @return collection of win conditions
*/
public <T extends AutoRefGoal> Set<T> getTeamGoals(Class<T> clazz)
{
Set<T> typedGoals = Sets.newHashSet();
for (AutoRefGoal goal : goals)
if (clazz.isInstance(goal)) typedGoals.add((T) goal);
return typedGoals;
}
Set<AutoRefObjective> scoreboardObjectives;
public void updateObjectives()
{
if (scoreboardObjectives != null)
for (AutoRefObjective obj : scoreboardObjectives)
obj.update();
}
// does a provided search string match this team?
public int matches(String needle)
{
if (needle == null) return 0;
needle = needle.toLowerCase();
String a = name, b = customName;
if (b != null && needle.contains(b.toLowerCase())) return b.length();
if (a != null && needle.contains(a.toLowerCase())) return a.length();
return 0;
}
public void startMatch()
{
// if there is no match associated, most of this work is moot
assert getMatch() != null : "Match is null";
for (AutoRefGoal goal : goals) if (goal.hasItem())
goal.setItemStatus(AutoRefGoal.ItemStatus.NONE);
for (AutoRefPlayer apl : getPlayers())
{
Player player = apl.getPlayer();
if (player != null && !getMatch().inStartRegion(player.getLocation()))
player.teleport(getMatch().getPlayerSpawn(player));
apl.heal();
apl.updateCarrying();
}
// save all players currently on team
playersCache.addAll(players);
}
// a factory for processing config xml
public static AutoRefTeam fromElement(Element elt, AutoRefMatch match)
{
// the element we are building on needs to be a team element
assert "team".equals(elt.getName().toLowerCase());
AutoRefTeam newTeam = new AutoRefTeam();
newTeam.color = ChatColor.RESET;
newTeam.match = match;
// get name from map
if (null == (newTeam.name = elt.getChildTextTrim("name"))) return null;
String sbteam = elt.getAttributeValue("scoreboard");
if (sbteam != null)
{
if (sbteam.length() > 16) sbteam = sbteam.substring(0, 16);
newTeam.scoreboardTeamName = sbteam;
}
String clr = elt.getAttributeValue("color");
String maxsz = elt.getAttributeValue("maxsize");
String minsz = elt.getAttributeValue("minsize");
if (clr != null) try
{ newTeam.color = ChatColor.valueOf(clr.toUpperCase()); }
catch (IllegalArgumentException e) { }
// initialize this team for referees
match.messageReferees("team", newTeam.getName(), "init");
match.messageReferees("team", newTeam.getName(), "color", newTeam.color.toString());
// get the min and max size from the team tag
if (maxsz != null) newTeam.maxsize = Integer.parseInt(maxsz);
if (minsz != null) newTeam.minsize = Integer.parseInt(minsz);
if (elt.getAttributeValue("kit") != null)
{
newTeam.setKit(match.getKit(elt.getAttributeValue("kit")));
if (!Boolean.parseBoolean(match.getWorld().getGameRuleValue("keepInventory")))
{
AutoReferee.log("A kit has been specified with keepInventory=false", Level.WARNING);
AutoReferee.log("To turn this feature on, type '/gamerule keepInventory true'", Level.WARNING);
AutoReferee.log("This map should (maybe) be reconfigured with keepInventory", Level.WARNING);
}
}
Element spawn = elt.getChild("spawn");
if (spawn != null) for (Element reg : spawn.getChildren())
newTeam.addSpawnRegion(AutoRefRegion.fromElement(match, reg));
if (elt.getAttribute("lives") != null)
try { newTeam.playerlives = Integer.parseInt(elt.getAttributeValue("lives").trim()); }
catch (NumberFormatException e) { e.printStackTrace(); }
newTeam.setupScoreboard();
newTeam.players = Sets.newHashSet();
return newTeam;
}
// a factory for creating raw teams
public static AutoRefTeam create(AutoRefMatch match, String name, ChatColor color)
{
AutoRefTeam newTeam = new AutoRefTeam();
newTeam.color = color;
newTeam.match = match;
newTeam.name = name;
// initialize this team for referees
match.messageReferees("team", newTeam.getName(), "init");
match.messageReferees("team", newTeam.getName(), "color", newTeam.color.toString());
newTeam.setupScoreboard();
newTeam.players = Sets.newHashSet();
return newTeam;
}
protected void setupScoreboard()
{
String sbteam = this.getScoreboardTeamName();
// set team data on spectators' scoreboard
infoboardTeam = match.getInfoboard().registerNewTeam(sbteam);
infoboardTeam.setPrefix(color.toString());
infoboardTeam.setDisplayName(getName());
// set team data on players' scoreboard
AutoReferee.log("Setting up scoreboard for " + sbteam);
scoreboardTeam = match.getScoreboard().getTeam(sbteam);
if (scoreboardTeam == null && this.scoreboardTeamName == null)
scoreboardTeam = match.getScoreboard().registerNewTeam(sbteam);
if (scoreboardTeam != null)
{
scoreboardTeam.setPrefix(color.toString());
scoreboardTeam.setDisplayName(getName());
// this stuff is only really necessary for the players themselves
scoreboardTeam.setAllowFriendlyFire(match.allowFriendlyFire());
scoreboardTeam.setCanSeeFriendlyInvisibles(true);
}
}
public Element toElement()
{
Element elt = new Element("team");
elt.addContent(new Element("name").setText(getDefaultName()));
if (scoreboardTeamName != null)
elt.setAttribute("scoreboard", scoreboardTeamName);
if (this.getColor() != ChatColor.RESET) elt.setAttribute("color", this.getColor().name());
if (this.maxsize != null) elt.setAttribute("maxsize", Integer.toString(this.maxsize));
if (this.minsize != null) elt.setAttribute("minsize", Integer.toString(this.minsize));
if (this.playerlives > 0) elt.setAttribute("lives", Integer.toString(this.playerlives));
PlayerKit teamKit = this.getKit();
if (teamKit != null) elt.setAttribute("kit", teamKit.getName());
if (this.spawnRegions != null)
{
Element spawnElement = new Element("spawn");
for (AutoRefRegion reg : this.spawnRegions)
spawnElement.addContent(reg.toElement());
elt.addContent(spawnElement);
}
return elt;
}
private PlayerKit startKit = null;
public PlayerKit getKit()
{ return startKit; }
public void setKit(PlayerKit kit)
{ this.startKit = kit; }
/**
* Gets a player from this team by name.
*
* @return player object if one exists, otherwise null
*/
public AutoRefPlayer getPlayer(String name)
{
AutoRefPlayer bapl = null;
if (name != null)
{
int score, b = Integer.MAX_VALUE;
for (AutoRefPlayer apl : players)
{
score = apl.nameSearch(name);
if (score < b) { b = score; bapl = apl; }
}
}
return bapl;
}
/**
* Gets a player from this team associated with the specified player.
*
* @return player object if one exists, otherwise null
*/
public AutoRefPlayer getPlayer(Player player)
{ return player == null ? null : getPlayer(player.getName()); }
protected void addPlayer(AutoRefPlayer apl)
{
if (scoreboardTeam != null) scoreboardTeam.addPlayer(Bukkit.getOfflinePlayer(apl.getName()));
if ( infoboardTeam != null) infoboardTeam.addPlayer(Bukkit.getOfflinePlayer(apl.getName()));
apl.setTeam(this); this.players.add(apl);
if (this.getMatch() != null && this.getMatch().getCurrentState().inProgress())
this.playersCache.add(apl);
}
protected boolean removePlayer(AutoRefPlayer apl)
{
if (scoreboardTeam != null) scoreboardTeam.removePlayer(Bukkit.getOfflinePlayer(apl.getName()));
if ( infoboardTeam != null) infoboardTeam.removePlayer(Bukkit.getOfflinePlayer(apl.getName()));
return this.players.remove(apl);
}
/**
* Adds a player to this team. Players may not be added to teams if the match
* is already in progress.
*
* @return true if player was successfully added, otherwise false
*/
public boolean join(Player player, PlayerTeamJoinEvent.Reason reason)
{ return join(player, reason, false); }
/**
* Adds a player to this team.
*
* @param force force join operation, even if match is in progress
* @return true if player was successfully added, otherwise false
*/
public boolean join(Player player, PlayerTeamJoinEvent.Reason reason, boolean force)
{
PlayerTeamJoinEvent event = new PlayerTeamJoinEvent(player, this, reason);
AutoReferee.callEvent(event);
if (event.isCancelled()) return false;
// if this player is using the client mod and is not an op, they may not join
if (!player.isOp() && PlayerUtil.hasClientMod(player))
{
if (!getMatch().isReferee(player))
player.sendMessage("You may not join a team with a modified client");
String warning = ChatColor.DARK_GRAY + player.getName() + " attempted to join "
+ this.getDisplayName() + ChatColor.DARK_GRAY + " with a modified client";
for (Player ref : getMatch().getReferees(true)) ref.sendMessage(warning);
return false;
}
// create an APL object for this player.
AutoRefPlayer apl = new AutoRefPlayer(player, this);
if (this.playerlives > 0) apl.setLivesRemaining(this.playerlives);
// quit if they are already on this team
if (players.contains(apl)) return true;
// if there is no match object, drop out here
if (match == null) return false;
// if the match is in progress, no one may join
if (!match.getCurrentState().isBeforeMatch() && !force) return false;
// prepare the player
if (!match.getCurrentState().inProgress() && !this.spawnRegions.isEmpty())
player.teleport(this.getSpawnLocation());
Location bed = player.getBedSpawnLocation();
if (bed != null && bed.getWorld() != match.getWorld())
player.setBedSpawnLocation(null);
this.addPlayer(apl);
match.messageReferees("team", getName(), "player", "+" + apl.getName());
match.messageReferees("player", apl.getName(), "login");
match.updatePlayerList();
match.broadcast(apl.getDisplayName() + " has joined " + getDisplayName());
match.setupSpectators(player);
match.checkTeamsReady();
return true;
}
/**
* Removes a player from this team. Players may not be removed from teams if the
* match is already in progress.
*
* @return true if player was successfully removed, otherwise false
*/
public boolean leave(Player player)
{ return leave(player, false); }
/**
* Removes a player from this team.
*
* @param force force leave operation, even if match is in progress
* @return true if player was successfully removed, otherwise false
*/
public boolean leave(Player player, boolean force)
{
PlayerTeamLeaveEvent event = new PlayerTeamLeaveEvent(player, this);
AutoReferee.callEvent(event);
if (event.isCancelled()) return false;
// if the match is in progress, no one may leave their team
if (!match.getCurrentState().isBeforeMatch() && !force &&
match.getReferees().size() > 0) return false;
String name = match.getDisplayName(player);
if (!this.leaveQuietly(player)) return false;
match.broadcast(name + " has left " + getDisplayName());
return true;
}
/**
* Removes a player from this team quietly.
*
* @return true if player was successfully removed, otherwise false
*/
public boolean leaveQuietly(Player player)
{
// create an APL object for this player.
AutoRefPlayer apl = new AutoRefPlayer(player);
if (!this.removePlayer(apl)) return false;
match.updatePlayerList();
// by the time this is actually called, they may have left the world to join
// a different match. this teleport shouldn't occur if they aren't in this world
if (player.getWorld() == match.getWorld() && !match.inStartRegion(player.getLocation()))
player.teleport(match.getWorldSpawn());
match.messageReferees("team", getName(), "player", "-" + apl.getName());
match.setupSpectators(player);
match.checkTeamsReady();
return true;
}
/**
* Returns distance from location to this team's closest region.
*
* @return distance
*/
public double distanceToClosestRegion(Location loc)
{
double distance = match.distanceToStartRegion(loc);
Set<AutoRefRegion> regions = getRegions();
if (regions != null) for ( AutoRefRegion reg : regions ) if (distance > 0)
distance = Math.min(distance, reg.distanceToRegion(loc));
return distance;
}
/**
* Checks if players on this team can be in a given location, including sneak distance.
*
* @return true if location is valid, otherwise false
*/
public boolean canEnter(Location loc)
{ return canEnter(loc, ZoneListener.SNEAK_DISTANCE); }
/**
* Checks if players on this team can be in a given location, within a specified distance.
*
* @param distance maximum distance a player may move from this location
* @return true if location is valid, otherwise false
*/
public boolean canEnter(Location loc, Double distance)
{
double bestdist = match.distanceToStartRegion(loc);
Set<AutoRefRegion> regions = getRegions();
if (regions != null) for ( AutoRefRegion reg : regions ) if (bestdist > 0)
{
bestdist = Math.min(bestdist, reg.distanceToRegion(loc));
if (reg.is(AutoRefRegion.Flag.NO_ENTRY) &&
reg.distanceToRegion(loc) <= distance) return false;
}
return bestdist <= distance;
}
/**
* Checks if a region is marked with a specific region flag.
*
* @return true if location contains flag, otherwise false
*/
public boolean hasFlag(Block b, AutoRefRegion.Flag flag)
{ return hasFlag(b, flag, flag.defaultValue); }
/**
* Checks if a region is marked with a specific region flag.
*
* @return true if location contains flag, otherwise false
*/
public boolean hasFlag(Block b, AutoRefRegion.Flag flag, boolean def)
{ return hasFlag(b.getLocation().clone().add(0.5, 0.5, 0.5), flag, def); }
/**
* Checks if a region is marked with a specific region flag.
*
* @return true if location contains flag, otherwise false
*/
public boolean hasFlag(Location loc, AutoRefRegion.Flag flag)
{ return hasFlag(loc, flag, flag.defaultValue); }
/**
* Checks if a region is marked with a specific region flag.
*
* @return true if location contains flag, otherwise false
*/
public boolean hasFlag(Location loc, AutoRefRegion.Flag flag, boolean def)
{
// check start region flags
if (getMatch().inStartRegion(loc))
return getMatch().getStartRegionFlags().contains(flag);
boolean is = def; Set<AutoRefRegion> regions = getRegions();
if (regions != null) for ( AutoRefRegion reg : regions )
if (reg.contains(loc)) { is = false; if (reg.is(flag)) return true; }
return is;
}
/**
* Sets a new win condition.
*/
public void addGoal(Element elt)
{ this.addGoal(AutoRefGoal.fromElement(this, elt)); }
/**
* Sets a new win condition.
*/
public void addGoal(AutoRefGoal goal)
{
if (goal == null) return;
goals.add(goal);
for (Player ref : getMatch().getReferees(false))
goal.updateReferee(ref);
// broadcast the update
for (Player cfg : getMatch().getWorld().getPlayers()) if (cfg.hasPermission("autoreferee.configure"))
cfg.sendMessage(goal.toString() + " is now a win condition for " + getDisplayName());
}
/**
* Gets a list of team objectives for this match.
*
* @return collection of block types to be retrieved
*/
public Set<BlockData> getObjectives()
{
Set<BlockData> objectives = Sets.newHashSet();
for (AutoRefGoal goal : goals)
if (goal.hasItem()) objectives.add(goal.getItem());
objectives.remove(BlockData.AIR);
return objectives;
}
/**
* Gets a list of team objectives for this match.
*
* @return collection of block types to be retrieved
*/
public Map<BlockData, AutoRefGoal> getGoalsByObjective()
{
Map<BlockData, AutoRefGoal> goalsByObjective = Maps.newHashMap();
for (AutoRefGoal goal : goals)
if (goal.hasItem()) goalsByObjective.put(goal.getItem(), goal);
goalsByObjective.remove(BlockData.AIR);
return goalsByObjective;
}
public boolean canCraft(BlockData bdata)
{
for (AutoRefGoal goal : goals)
if (goal.hasItem() && goal.getItem().equals(bdata) && goal.canCraftItem())
return false;
return true;
}
private void changeObjectiveStatus(AutoRefGoal goal, AutoRefGoal.ItemStatus status)
{
if (!goal.hasItem() || goal.getItemStatus() == status) return;
getMatch().messageReferees("team", this.getName(), "state",
goal.getItem().serialize(), status.toString());
goal.setItemStatus(status);
ObjectiveUpdateEvent event = new ObjectiveUpdateEvent(goal);
AutoReferee.callEvent(event);
}
protected void updateBlockGoals()
{
objloop: for (BlockGoal goal : this.getTeamGoals(BlockGoal.class))
{
if (goal.isSatisfied(getMatch()))
{ changeObjectiveStatus(goal, AutoRefGoal.ItemStatus.TARGET); continue objloop; }
for (AutoRefPlayer apl : getPlayers())
{
if (!apl.getCarrying().containsKey(goal.getItem())) continue;
changeObjectiveStatus(goal, AutoRefGoal.ItemStatus.CARRYING); continue objloop;
}
if (goal.getItemStatus() != AutoRefGoal.ItemStatus.NONE)
{ changeObjectiveStatus(goal, AutoRefGoal.ItemStatus.SEEN); continue objloop; }
}
}
public double getObjectiveScore()
{
double score = 0.0f;