This repository was archived by the owner on Mar 18, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathPlayer.java
More file actions
991 lines (816 loc) · 26.6 KB
/
Player.java
File metadata and controls
991 lines (816 loc) · 26.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
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package simpleserver;
import static simpleserver.lang.Translations.t;
import static simpleserver.util.Util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.xml.sax.SAXException;
import simpleserver.Coordinate.Dimension;
import simpleserver.bot.BotController.ConnectException;
import simpleserver.bot.Giver;
import simpleserver.bot.Teleporter;
import simpleserver.command.ExternalCommand;
import simpleserver.command.PlayerCommand;
import simpleserver.config.KitList.Kit;
import simpleserver.config.data.Stats.StatField;
import simpleserver.config.xml.Area;
import simpleserver.config.xml.CommandConfig;
import simpleserver.config.xml.CommandConfig.Forwarding;
import simpleserver.config.xml.Event;
import simpleserver.config.xml.Group;
import simpleserver.config.xml.Permission;
import simpleserver.message.AbstractChat;
import simpleserver.message.Chat;
import simpleserver.message.GlobalChat;
import simpleserver.message.Message;
import simpleserver.stream.Encryption;
import simpleserver.stream.Encryption.ClientEncryption;
import simpleserver.stream.Encryption.ServerEncryption;
import simpleserver.stream.StreamTunnel;
public class Player {
private final long connected;
private final Socket extsocket;
private final Server server;
private Socket intsocket;
private StreamTunnel serverToClient;
private StreamTunnel clientToServer;
private Watchdog watchdog;
public ServerEncryption serverEncryption = new Encryption.ServerEncryption();
public ClientEncryption clientEncryption = new Encryption.ClientEncryption();
private String name = null;
private String uuid = null;
private String renameName = null;
private String connectionHash;
private boolean closed = false;
private boolean isKicked = false;
private Action attemptedAction;
private boolean instantDestroy = false;
private boolean godMode = false;
private String kickMsg = null;
public Position position;
private Position deathPlace;
private float health = 0;
private short experience = 0;
private int group = 0;
private int entityId = 0;
private Group groupObject = null;
private boolean isRobot = false;
// player is not authenticated with minecraft.net:
private boolean guest = false;
private boolean usedAuthenticator = false;
private int blocksPlaced = 0;
private int blocksDestroyed = 0;
private Player reply = null;
private String lastCommand = "";
private AbstractChat chatType;
private Queue<String> messages = new ConcurrentLinkedQueue<String>();
private Queue<String> forwardMessages = new ConcurrentLinkedQueue<String>();
private Queue<PlayerVisitRequest> visitreqs = new ConcurrentLinkedQueue<PlayerVisitRequest>();
private Coordinate chestPlaced;
private Coordinate chestOpened;
private String nextChestName;
// temporary coordinate storage for /myarea command
public Coordinate areastart;
public Coordinate areaend;
private long lastTeleport;
private short experienceLevel;
public ConcurrentHashMap<String, String> vars; // temporary player-scope
// Script variables
private long lastEvent;
private HashSet<Area> currentAreas = new HashSet<Area>();
public Player(Socket inc, Server parent) {
connected = System.currentTimeMillis();
position = new Position();
server = parent;
chatType = new GlobalChat(this);
extsocket = inc;
vars = new ConcurrentHashMap<String, String>();
if (server.isRobot(getIPAddress())) {
println("Robot Heartbeat: " + getIPAddress() + ".");
isRobot = true;
} else {
println("IP Connection from " + getIPAddress() + "!");
}
if (server.isIPBanned(getIPAddress())) {
println("IP " + getIPAddress() + " is banned!");
cleanup();
return;
}
server.requestTracker.addRequest(getIPAddress());
try {
InetAddress localAddress = InetAddress.getByName(Server.addressFactory.getNextAddress());
intsocket = new Socket(InetAddress.getByName(null),
server.options.getInt("internalPort"),
localAddress, 0);
} catch (Exception e) {
try {
intsocket = new Socket(InetAddress.getByName(null), server.options.getInt("internalPort"));
} catch (Exception E) {
e.printStackTrace();
if (server.config.properties.getBoolean("exitOnFailure")) {
server.stop();
} else {
server.restart();
}
cleanup();
return;
}
}
watchdog = new Watchdog();
try {
serverToClient = new StreamTunnel(intsocket.getInputStream(), extsocket.getOutputStream(), true, this);
clientToServer = new StreamTunnel(extsocket.getInputStream(), intsocket.getOutputStream(), false, this);
} catch (IOException e) {
e.printStackTrace();
cleanup();
return;
}
if (isRobot) {
server.addRobotPort(intsocket.getLocalPort());
}
watchdog.start();
}
public boolean setName(String name) {
renameName = server.data.players.getRenameName(name);
name = name.trim();
if (name.length() == 0 || this.name != null) {
kick(t("Invalid Name!"));
return false;
}
if (name.equals("Player")) {
kick(t("Too many guests in server!"));
return false;
}
if (!guest && server.config.properties.getBoolean("useWhitelist")
&& !server.whitelist.isWhitelisted(name)) {
kick(t("You are not whitelisted!"));
return false;
}
if (server.playerList.findPlayerExact(name) != null) {
kick(t("Player already in server!"));
return false;
}
this.name = name;
updateGroup();
watchdog.setName("PlayerWatchdog-" + name);
server.connectionLog("player", extsocket, name);
if (server.numPlayers() == 0) {
server.time.set();
}
server.playerList.addPlayer(this);
return true;
}
public void setUuid(String u) {
uuid = u;
}
public String getUuid() {
return uuid;
}
public String getName() {
return renameName;
}
public String getName(boolean original) {
return (original) ? name : renameName;
}
public String getRealName() {
return server.data.players.getRealName(name);
}
public void updateRealName(String name) {
server.data.players.setRealName(name);
}
public String getConnectionHash() {
if (connectionHash == null) {
connectionHash = server.nextHash();
}
return connectionHash;
}
public String getLoginHash() throws NoSuchAlgorithmException, UnsupportedEncodingException {
return clientEncryption.getLoginHash(getConnectionHash());
}
public double distanceTo(Player player) {
return Math.sqrt(Math.pow(x() - player.x(), 2) + Math.pow(y() - player.y(), 2) + Math.pow(z() - player.z(), 2));
}
public long getConnectedAt() {
return connected;
}
public boolean isAttemptLock() {
return attemptedAction == Action.Lock;
}
public void setAttemptedAction(Action action) {
attemptedAction = action;
}
public boolean instantDestroyEnabled() {
return instantDestroy;
}
public void toggleInstantDestroy() {
instantDestroy = !instantDestroy;
}
public Server getServer() {
return server;
}
public void setState(int i) {
serverToClient.setState(i);
clientToServer.setState(i);
}
public void setChat(AbstractChat chat) {
chatType = chat;
}
public String getChatRoom() {
return chatType.toString();
}
public void sendMessage(String message) {
sendMessage(chatType, message);
}
public void sendMessage(String message, boolean build) {
sendMessage(chatType, message, build);
}
public void sendMessage(Chat messageType, String message) {
server.getMessager().propagate(messageType, message);
}
public void sendMessage(Chat messageType, String message, boolean build) {
server.getMessager().propagate(messageType, message, build);
}
public void forwardMessage(String message) {
forwardMessages.add(message);
}
public boolean hasForwardMessages() {
return !forwardMessages.isEmpty();
}
public boolean hasMessages() {
return !messages.isEmpty();
}
public void addMessage(Color color, String format, Object... args) {
addMessage(color, String.format(format, args));
}
public void addMessage(Color color, String message) {
addMessage(color + message);
}
public void addMessage(String format, Object... args) {
addMessage(String.format(format, args));
}
public void addCaptionedMessage(String caption, String format, Object... args) {
addMessage("%s%s: %s%s", Color.GRAY, caption, Color.WHITE, String.format(format, args));
}
public void addMessage(String msg) {
messages.add(new Message(msg).buildMessage(true));
}
public void addTMessage(Color color, String format, Object... args) {
addMessage(color + t(format, args));
}
public void addTMessage(Color color, String message) {
addMessage(color + t(message));
}
public void addTMessage(String msg) {
addMessage(t(msg));
}
public void addTCaptionedTMessage(String caption, String format, Object... args) {
addMessage("%s%s: %s%s", Color.GRAY, t(caption), Color.WHITE, t(format, args));
}
public void addTCaptionedMessage(String caption, String format, Object... args) {
addMessage("%s%s: %s%s", Color.GRAY, t(caption),
Color.WHITE, String.format(format, args));
}
public String getForwardMessage() {
return forwardMessages.remove();
}
public String getMessage() {
return messages.remove();
}
public void addVisitRequest(Player source) {
visitreqs.add(new PlayerVisitRequest(source));
}
public void handleVisitRequests() {
while (visitreqs.size() > 0) {
PlayerVisitRequest req = visitreqs.remove();
if (System.currentTimeMillis() < req.timestamp + 10000 && server.findPlayerExact(req.source.getName()) != null) {
req.source.addTMessage(Color.GRAY, "Request accepted!");
req.source.teleportTo(this);
}
}
}
public void kick(String reason) {
kickMsg = reason;
isKicked = true;
serverToClient.stop();
clientToServer.stop();
}
public boolean isKicked() {
return isKicked;
}
public void setKicked(boolean b) {
isKicked = b;
}
public String getKickMsg() {
return kickMsg;
}
public boolean isMuted() {
return server.mutelist.isMuted(name);
}
public boolean isRobot() {
return isRobot;
}
public boolean godModeEnabled() {
return godMode;
}
public void toggleGodMode() {
godMode = !godMode;
}
public int getEntityId() {
return entityId;
}
public void setEntityId(int readInt) {
entityId = readInt;
}
public int getGroupId() {
return group;
}
public Group getGroup() {
return groupObject;
}
public void setGuest(boolean guest) {
this.guest = guest;
}
public boolean isGuest() {
return guest;
}
public void setUsedAuthenticator(boolean usedAuthenticator) {
this.usedAuthenticator = usedAuthenticator;
}
public boolean usedAuthenticator() {
return usedAuthenticator;
}
public String getIPAddress() {
return extsocket.getInetAddress().getHostAddress();
}
public InetAddress getInetAddress() {
return extsocket.getInetAddress();
}
public boolean ignoresChestLocks() {
return groupObject.ignoreChestLocks;
}
private void setDeathPlace(Position deathPosition) {
deathPlace = deathPosition;
}
public Position getDeathPlace() {
return deathPlace;
}
public float getHealth() {
return health;
}
public void updateHealth(float health) {
this.health = health;
if (health <= 0) {
setDeathPlace(new Position(position()));
}
}
public short getExperience() {
return experience;
}
public short getExperienceLevel() {
return experienceLevel;
}
public void updateExperience(float bar, short level, short experience) {
experienceLevel = level;
this.experience = experience;
}
public double x() {
return position.x;
}
public double y() {
return position.y;
}
public double z() {
return position.z;
}
public Coordinate position() {
return position.coordinate();
}
public float yaw() {
return position.yaw;
}
public float pitch() {
return position.pitch;
}
public String parseCommand(String message, boolean overridePermissions) {
// TODO: Handle aliases of external commands
if (closed) {
return null;
}
// Repeat last command
if (message.equals(server.getCommandParser().commandPrefix() + "!")) {
message = lastCommand;
} else {
lastCommand = message;
}
String commandName = message.split(" ")[0].substring(1).toLowerCase();
String args = commandName.length() + 1 >= message.length() ? "" : message.substring(commandName.length() + 2);
CommandConfig config = server.config.commands.getTopConfig(commandName);
String originalName = config == null ? commandName : config.originalName;
PlayerCommand command = server.resolvePlayerCommand(originalName, groupObject);
if (config != null && !overridePermissions) {
Permission permission = server.config.getCommandPermission(config.name, args, position.coordinate());
if (!permission.contains(this)) {
addTMessage(Color.RED, "Insufficient permission.");
return null;
}
}
try {
if (server.options.getBoolean("enableEvents") && config.event != null) {
Event e = server.eventhost.findEvent(config.event);
if (e != null) {
ArrayList<String> arguments = new ArrayList<String>();
if (!args.equals("")) {
arguments = new ArrayList<String>(java.util.Arrays.asList(args.split("\\s+")));
}
server.eventhost.execute(e, this, true, arguments);
} else {
System.out.println("Error in player command " + originalName + ": Event " + config.event + " not found!");
}
}
} catch (NullPointerException e) {
System.out.println("Error evaluating player command: " + originalName);
}
if (!(command instanceof ExternalCommand) && (config == null || config.forwarding != Forwarding.ONLY)) {
command.execute(this, message);
}
if (command instanceof ExternalCommand) {
// commands with bound events have to be forwarded explicitly
// (to prevent unknown command error by server)
if (config.event != null && config.forwarding == Forwarding.NONE) {
return null;
} else {
return "/" + originalName + " " + args;
}
} else if ((config != null && config.forwarding != Forwarding.NONE) || server.config.properties.getBoolean("forwardAllCommands")) {
return message;
} else {
return null;
}
}
public void execute(Class<? extends PlayerCommand> c) {
execute(c, "");
}
public void execute(Class<? extends PlayerCommand> c, String arguments) {
server.getCommandParser().getPlayerCommand(c).execute(this, "a " + arguments);
}
public void teleportTo(Player target) {
server.runCommand("tp", getName() + " " + target.getName());
}
public void sendMOTD() {
String[] lines = server.motd.getMOTD().split("\\r?\\n");
for (String line : lines) {
addMessage(line);
}
}
public void give(int id, int amount) {
String baseCommand = getName() + " " + id + " ";
for (int c = 0; c < amount / 64; ++c) {
server.runCommand("give", baseCommand + 64);
}
if (amount % 64 != 0) {
server.runCommand("give", baseCommand + amount % 64);
}
}
public void give(int id, short damage, int amount) throws ConnectException {
if (damage == 0) {
give(id, amount);
} else {
Giver giver = new Giver(this);
for (int c = 0; c < amount / 64; ++c) {
giver.add(id, 64, damage);
}
if (amount % 64 != 0) {
giver.add(id, amount % 64, damage);
}
server.bots.connect(giver);
}
}
public void give(Kit kit) throws ConnectException {
Giver giver = new Giver(this);
int invSize = 45;
int slot = invSize;
for (Kit.Entry e : kit.items) {
if (e.damage() == 0) {
give(e.item(), e.amount());
} else {
int restAmount = e.amount();
while (restAmount > 0 && --slot >= 0) {
giver.add(e.item(), Math.min(restAmount, 64), e.damage());
restAmount -= 64;
if (slot == 0) {
slot = invSize;
server.bots.connect(giver);
giver = new Giver(this);
}
}
}
}
if (slot != invSize) {
server.bots.connect(giver);
}
}
public void updateGroup() {
try {
groupObject = server.config.getGroup(this);
} catch (SAXException e) {
println("A player could not be assigned to any group. (" + e + ")");
kick("You could not be asigned to any group.");
return;
}
group = groupObject.id;
}
public void placedBlock() {
blocksPlaced += 1;
}
public void destroyedBlock() {
blocksDestroyed += 1;
}
public Integer[] stats() {
Integer[] stats = new Integer[4];
stats[0] = (int) (System.currentTimeMillis() - connected) / 1000 / 60;
stats[1] = server.data.players.stats.get(this, StatField.PLAY_TIME) + stats[0];
stats[2] = server.data.players.stats.add(this, StatField.BLOCKS_PLACED, blocksPlaced);
stats[3] = server.data.players.stats.add(this, StatField.BLOCKS_DESTROYED, blocksDestroyed);
blocksPlaced = 0;
blocksDestroyed = 0;
server.data.save();
return stats;
}
public void setReply(Player answer) {
// set Player to reply with !reply command
reply = answer;
}
public Player getReply() {
return reply;
}
public void close() {
if (serverToClient != null) {
serverToClient.stop();
}
if (clientToServer != null) {
clientToServer.stop();
}
if (name != null) {
server.authenticator.unbanLogin(this);
if (usedAuthenticator) {
if (guest) {
server.authenticator.releaseGuestName(name);
} else {
server.authenticator.rememberAuthentication(name, getIPAddress());
}
} else if (guest) {
if (isKicked) {
server.authenticator.releaseGuestName(name);
} else {
server.authenticator.rememberGuest(name, getIPAddress());
}
}
server.data.players.stats.add(this, StatField.PLAY_TIME, (int) (System.currentTimeMillis() - connected) / 1000 / 60);
server.data.players.stats.add(this, StatField.BLOCKS_DESTROYED, blocksDestroyed);
server.data.players.stats.add(this, StatField.BLOCKS_PLACED, blocksPlaced);
server.data.save();
server.playerList.removePlayer(this);
name = renameName = null;
}
}
private void cleanup() {
if (!closed) {
closed = true;
entityId = 0;
close();
try {
extsocket.close();
} catch (Exception e) {
}
try {
intsocket.close();
} catch (Exception e) {
}
if (!isRobot) {
println("Socket Closed: "
+ extsocket.getInetAddress().getHostAddress());
}
}
}
private class PlayerVisitRequest {
public Player source;
public long timestamp;
public PlayerVisitRequest(Player source) {
timestamp = System.currentTimeMillis();
this.source = source;
}
}
private final class Watchdog extends Thread {
@Override
public void run() {
while (serverToClient.isAlive() || clientToServer.isAlive()) {
if (!serverToClient.isActive() || !clientToServer.isActive()) {
println("Disconnecting " + getIPAddress()
+ " due to inactivity.");
close();
break;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
cleanup();
}
}
public void placingChest(Coordinate coord) {
chestPlaced = coord;
}
public boolean placedChest(Coordinate coordinate) {
return chestPlaced != null && chestPlaced.equals(coordinate);
}
public void openingChest(Coordinate coordinate) {
chestOpened = coordinate;
}
public Coordinate openedChest() {
return chestOpened;
}
public void setChestName(String name) {
nextChestName = name;
}
public String nextChestName() {
return nextChestName;
}
public enum Action {
Lock, Unlock, Rename;
}
public boolean isAttemptingUnlock() {
return attemptedAction == Action.Unlock;
}
public void setDimension(Dimension dimension) {
position.updateDimension(dimension);
}
public Dimension getDimension() {
return position.dimension();
}
public void teleport(Coordinate coordinate) throws ConnectException, IOException {
teleport(new Position(coordinate));
}
public void teleport(Position position) throws ConnectException, IOException {
if (position.dimension() == getDimension()) {
server.bots.connect(new Teleporter(this, position));
} else {
addTMessage(Color.RED, "You're not in the same dimension as the specified warppoint.");
}
}
public void teleportSelf(Coordinate coordinate) {
teleportSelf(new Position(coordinate));
}
public void teleportSelf(Position position) {
try {
teleport(position);
} catch (Exception e) {
addTMessage(Color.RED, "Teleporting failed.");
return;
}
lastTeleport = System.currentTimeMillis();
}
private int cooldownLeft() {
int cooldown = getGroup().cooldown();
if (lastTeleport > System.currentTimeMillis() - cooldown) {
return (int) (cooldown - System.currentTimeMillis() + lastTeleport);
} else {
return 0;
}
}
public synchronized void teleportWithWarmup(Coordinate coordinate) {
teleportWithWarmup(new Position(coordinate));
}
public synchronized void teleportWithWarmup(Position position) {
int cooldown = cooldownLeft();
if (lastTeleport < 0) {
addTMessage(Color.RED, "You are already waiting for a teleport.");
} else if (cooldown > 0) {
addTMessage(Color.RED, "You have to wait %d seconds before you can teleport again.", cooldown / 1000);
} else {
int warmup = getGroup().warmup();
if (warmup > 0) {
lastTeleport = -1;
Timer timer = new Timer();
timer.schedule(new Warmup(position), warmup);
addTMessage(Color.GRAY, "You will be teleported in %s seconds.", warmup / 1000);
} else {
teleportSelf(position);
}
}
}
public void checkAreaEvents() {
HashSet<Area> areas = new HashSet<Area>(server.config.dimensions.areas(position()));
HashSet<Area> areasCopy = new HashSet<Area>(areas);
HashSet<Area> oldAreas = currentAreas;
areasCopy.removeAll(oldAreas); // -> now contains only newly entered areas
oldAreas.removeAll(areas); // -> now contains only areas not present anymore
for (Area a : areasCopy) { // run area onenter events
if (a.event == null) {
continue;
}
Event e = server.eventhost.findEvent(a.event);
if (e != null) {
ArrayList<String> args = new ArrayList<String>();
args.add("enter");
args.add(a.name);
server.eventhost.execute(e, this, true, args);
} else {
System.out.println("Error in area " + a.name + "/event: Event " + a.event + " not found!");
}
}
for (Area a : oldAreas) { // run area onleave events
if (a.event == null) {
continue;
}
Event e = server.eventhost.findEvent(a.event);
if (e != null) {
ArrayList<String> args = new ArrayList<String>();
args.add("leave");
args.add(a.name);
server.eventhost.execute(e, this, true, args);
} else {
System.out.println("Error in area " + a.name + "/event: Event " + a.event + " not found!");
}
}
currentAreas = areas;
}
public void checkLocationEvents() {
checkAreaEvents();
long currtime = System.currentTimeMillis();
if (currtime < lastEvent + 500) {
return;
}
Iterator<Event> it = server.eventhost.events.keySet().iterator();
while (it.hasNext()) {
Event ev = it.next();
if (!ev.type.equals("plate") || ev.coordinate == null) {
continue;
}
if (position.coordinate().equals(ev.coordinate)) { // matching -> execute
server.eventhost.execute(ev, this, false, null);
lastEvent = currtime;
}
}
}
public void checkButtonEvents(Coordinate c) {
long currtime = System.currentTimeMillis();
if (currtime < lastEvent + 500) {
return;
}
Iterator<Event> it = server.eventhost.events.keySet().iterator();
while (it.hasNext()) {
Event ev = it.next();
if (!ev.type.equals("button") || ev.coordinate == null) {
continue;
}
if ((new Coordinate(c.x(), c.y(), c.z(), position.dimension())).equals(ev.coordinate)) { // matching
// ->
// execute
server.eventhost.execute(ev, this, false, null);
lastEvent = currtime;
}
}
}
private final class Warmup extends TimerTask {
private final Position position;
private Warmup(Position position) {
super();
this.position = position;
}
@Override
public void run() {
teleportSelf(position);
}
}
}