Add basic game loop handling to the game server

This commit is contained in:
Melledy
2023-11-12 16:03:53 -08:00
parent 59c40437a4
commit c379b8dea3
2 changed files with 36 additions and 7 deletions

View File

@@ -531,6 +531,12 @@ public class Player {
}
}
public void onTick() {
}
// Database
public void save() {
if (this.uid <= 0) {
LunarCore.getLogger().error("Tried to save a player object without a uid!");
@@ -570,7 +576,7 @@ public class Player {
}
}
// Proto
// Protobuf serialization
public PlayerBasicInfo toProto() {
var proto = PlayerBasicInfo.newInstance()

View File

@@ -3,6 +3,8 @@ package emu.lunarcore.server.game;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import emu.lunarcore.Config.GameServerConfig;
import emu.lunarcore.LunarCore;
@@ -18,15 +20,15 @@ import kcp.highway.KcpServer;
import lombok.Getter;
public class GameServer extends KcpServer {
private final InetSocketAddress address;
private final GameServerConfig serverConfig;
private final RegionInfo info;
private final InetSocketAddress address;
@Getter
private final GameServerPacketHandler packetHandler;
private final Int2ObjectMap<Player> players;
private final Timer gameLoopTimer;
// Managers
@Getter private final GameServerPacketHandler packetHandler;
@Getter private final BattleService battleService;
@Getter private final DropService dropService;
@Getter private final InventoryService inventoryService;
@@ -47,6 +49,15 @@ public class GameServer extends KcpServer {
this.inventoryService = new InventoryService(this);
this.gachaService = new GachaService(this);
// Game loop
this.gameLoopTimer = new Timer();
this.gameLoopTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
onTick();
}
}, 0, 1000);
// Hook into shutdown event.
Runtime.getRuntime().addShutdownHook(new Thread(this::onShutdown));
}
@@ -98,6 +109,18 @@ public class GameServer extends KcpServer {
LunarCore.getLogger().info("Game Server started on " + address.getPort());
}
private void onTick() {
synchronized (this.players) {
for (Player player : this.players.values()) {
try {
player.onTick();
} catch (Exception e) {
LunarCore.getLogger().error("[UID: " + player.getUid() + "] Player tick error: ", e);
}
}
}
}
private void onShutdown() {
// Close server socket
this.stop();