diff --git a/src/main/java/mc/core/GameLoop.java b/src/main/java/mc/core/GameLoop.java new file mode 100644 index 0000000..86cc59a --- /dev/null +++ b/src/main/java/mc/core/GameLoop.java @@ -0,0 +1,65 @@ +/* + * DmitriyMX + * 2018-04-21 + */ +package mc.core; + +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.helpers.MessageFormatter; +import org.springframework.beans.factory.annotation.Autowired; + +@Slf4j +public class GameLoop extends Thread { + @Autowired + PlayerManager playerManager; + private int tps; + private long pause; + @Setter + private boolean traceTPS = false; + + public GameLoop() { + super(); + setTps(20); + } + + public void setTps(int tps) { + if (tps > 1000) { + log.warn("TPS can't be '{}'. Set 1000", tps); + tps = 1000; + } + this.tps = tps; + this.pause = (1000 / tps); + } + + @Override + public void run() { + int tpsFact = 0; + long lastTime = System.currentTimeMillis(); + + while (!isInterrupted()) { + if ((System.currentTimeMillis() - lastTime) > 1000) { + lastTime = System.currentTimeMillis(); + if (traceTPS) { + String msg = MessageFormatter.format("TPS: {}/{}", tpsFact, tps).getMessage(); + if (tpsFact < tps) { + log.warn(msg); + } else { + log.info(msg); + } + } + tpsFact = 0; + } + + long futureTime = System.currentTimeMillis() + pause; + + // code there // + + tpsFact++; + try { + Thread.sleep(futureTime - System.currentTimeMillis()); + } catch (InterruptedException ignored) { + } + } + } +} diff --git a/src/main/java/mc/core/Main.java b/src/main/java/mc/core/Main.java index bedc0b6..3b0f3bb 100644 --- a/src/main/java/mc/core/Main.java +++ b/src/main/java/mc/core/Main.java @@ -14,11 +14,17 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml"); + + GameLoop gameLoop = appContext.getBean(GameLoop.class); + gameLoop.start(); + Server server = appContext.getBean("server", Server.class); try { server.start(); } catch (StartServerException e) { log.error("Can't start server", e); } + + gameLoop.interrupt(); } } diff --git a/src/main/resources/spring.xml b/src/main/resources/spring.xml index 4d377ca..951ba58 100644 --- a/src/main/resources/spring.xml +++ b/src/main/resources/spring.xml @@ -11,6 +11,11 @@ + + + + +