Untitled
unknown
java
3 years ago
3.7 kB
6
Indexable
package ouengame; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferStrategy; import java.io.Serializable; import ouengame.utils.DebugUtil; import javax.swing.JPanel; public class OuenGame extends JPanel implements Runnable, Serializable { private static final long serialVersionUID = 710493813529287570L; private String frameRate = "..."; private String memoryUsage = "..."; private transient Thread t; private boolean running = false; public synchronized void start() { t = new Thread(this, "OuenGame"); t.setDaemon(true); t.start(); running = true; } public synchronized void stop() { try { t.join(); } catch (InterruptedException e) { t.interrupt(); } running = false; } public void run() { long lastTime = System.nanoTime(); long lastTimer = System.currentTimeMillis(); double ticks = 60; double nsPerTick = 1000000000 / ticks; double delta = 0; int frames = 0; while (running) { long currentTime = System.nanoTime(); delta += (currentTime - lastTime) / nsPerTick; lastTime = currentTime; while (delta >= 1) { ticks++; tick(); delta--; } render(); frames++; if (System.currentTimeMillis() - lastTimer >= 1000L) { long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); double usedPercentage = ((usedMemory * 1.0) / Runtime.getRuntime().totalMemory()) * 100; lastTimer += 1000L; /* Strings */ frameRate = String.format("%s FPS (%.2fms)", frames, 1000D / frames); memoryUsage = String.format("(%s%%) %s of %s KB", Math.round(usedPercentage), usedMemory / 1024, Runtime.getRuntime().totalMemory() / 1024); frames = 0; } } stop(); } public void tick() { /* * GAME UPDATES */ } public void render() { BufferStrategy bs = this.getBufferStrategy(); if (bs == null) { this.createBufferStrategy(3); return; } Graphics2D g2d = (Graphics2D) bs.getDrawGraphics(); g2d.setColor(Color.BLACK); g2d.fillRect(0, 0, getWidth(), getHeight()); /* * The following code is used to draw gameplay elements. */ /* * The following code is used to draw elements for debugging purposes */ if (OuenMain.debugMode) { g2d.setColor(Color.LIGHT_GRAY); /* BOTTOM LEFT */ g2d.drawString(frameRate, 2, (getHeight() - 12) - 2); g2d.drawString("OuenGame " + OuenMain.buildNumber, 2, getHeight() - 2); /* BOTTOM RIGHT */ g2d.drawString(DebugUtil.JAVA_VERSION, getWidth() - g2d.getFontMetrics() .stringWidth(DebugUtil.JAVA_VERSION) - 2, getHeight() - 2); g2d.drawString( memoryUsage, getWidth() - g2d.getFontMetrics().stringWidth(memoryUsage) - 2, (getHeight() - 12) - 2); } g2d.dispose(); bs.show(); } }
Editor is loading...