|
|
@@ -0,0 +1,75 @@
|
|
|
+package me.lethunderhawk.network;
|
|
|
+
|
|
|
+import com.esotericsoftware.kryonet.Client;
|
|
|
+import com.esotericsoftware.kryonet.Connection;
|
|
|
+import com.esotericsoftware.kryonet.Listener;
|
|
|
+import me.lethunderhawk.entity.Player;
|
|
|
+
|
|
|
+import java.io.IOException;
|
|
|
+import java.util.*;
|
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
|
+
|
|
|
+public class GameClient extends Listener {
|
|
|
+
|
|
|
+ private final Client client;
|
|
|
+ private final Map<UUID, Player> otherPlayers = new ConcurrentHashMap<>();
|
|
|
+ private final Player player;
|
|
|
+
|
|
|
+ public GameClient() {
|
|
|
+ this.player = new Player();
|
|
|
+ client = new Client();
|
|
|
+
|
|
|
+ client.start();
|
|
|
+
|
|
|
+ registerPackets();
|
|
|
+ }
|
|
|
+
|
|
|
+ private void registerPackets() {
|
|
|
+ NetworkRegister.register(client.getKryo());
|
|
|
+ }
|
|
|
+
|
|
|
+ public void connect(String ip) throws IOException {
|
|
|
+
|
|
|
+ client.connect(
|
|
|
+ 5000,
|
|
|
+ ip,
|
|
|
+ 54555,
|
|
|
+ 54777
|
|
|
+ );
|
|
|
+ client.addListener(this);
|
|
|
+ }
|
|
|
+
|
|
|
+ public void send(Object packet) {
|
|
|
+
|
|
|
+ client.sendUDP(packet);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void received (Connection connection, Object object) {
|
|
|
+ if(object instanceof Packets.PlayerLoginPacket packet) {
|
|
|
+ otherPlayers.put(packet.player.uuid, packet.player);
|
|
|
+ }
|
|
|
+
|
|
|
+ if(object instanceof Packets.PlayerPositionPacket packet) {
|
|
|
+ handlePlayerPosition(packet);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void handlePlayerPosition(Packets.PlayerPositionPacket packet) {
|
|
|
+ Player player = otherPlayers.computeIfAbsent(packet.player.uuid, uuid -> {
|
|
|
+ Player p = new Player();
|
|
|
+ p.uuid = uuid;
|
|
|
+ return p;
|
|
|
+ });
|
|
|
+ player.x = packet.x;
|
|
|
+ player.y = packet.y;
|
|
|
+ }
|
|
|
+
|
|
|
+ public Player getPlayer() {
|
|
|
+ return player;
|
|
|
+ }
|
|
|
+
|
|
|
+ public Map<UUID, Player> getOtherPlayers() {
|
|
|
+ return otherPlayers;
|
|
|
+ }
|
|
|
+}
|