Files
zp1/backend/src/main/java/com/zombie/game/server/GameLoop.java
2026-04-15 20:58:16 +08:00

47 lines
1.2 KiB
Java

package com.zombie.game.server;
import com.zombie.game.model.GameWorld;
public class GameLoop implements Runnable {
private String roomId;
private GameWorld world;
private GameWebSocketServer server;
private volatile boolean running;
private static final int TICK_RATE = 30;
private static final long TICK_INTERVAL = 1000 / TICK_RATE;
public GameLoop(String roomId, GameWorld world, GameWebSocketServer server) {
this.roomId = roomId;
this.world = world;
this.server = server;
this.running = true;
}
@Override
public void run() {
long lastTime = System.currentTimeMillis();
while (running) {
long now = System.currentTimeMillis();
long delta = now - lastTime;
if (delta >= TICK_INTERVAL) {
float dt = delta / 1000.0f;
world.update(dt);
server.broadcastGameState(roomId, world);
lastTime = now;
} else {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
break;
}
}
}
}
public void stop() {
running = false;
}
}