Skip to content

Commit

Permalink
optimizing the game Loop Moving the all components into the Game Clas…
Browse files Browse the repository at this point in the history
…s ( FPS counter )
  • Loading branch information
IamRishavDas committed Feb 19, 2024
1 parent a6bea51 commit 87a73b0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 18 deletions.
19 changes: 15 additions & 4 deletions NewGame/Game.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package NewGame;

public class Game implements Runnable{
public class Game implements Runnable {
private GameFrame gameFrame;
private GamePanel gamePanel;

Expand All @@ -15,20 +15,31 @@ public Game() {
startGameLoop();
}

private void startGameLoop(){
private void startGameLoop() {
gameThread = new Thread(this);
gameThread.start();
}

public void run(){
public void run() {
double timePerFrame = 1000000000.0 / FPS;
long lastFrame = System.nanoTime();
long now = System.nanoTime();

int frames = 0;
long lastCheck = System.currentTimeMillis();

while (true) {
now = System.nanoTime();
if(now - lastFrame > timePerFrame){
if (now - lastFrame > timePerFrame) {
gamePanel.repaint();
lastFrame = now;
frames++;
}

if ((System.currentTimeMillis() - lastCheck) >= 1000) {
lastCheck = System.currentTimeMillis();
System.out.println("FPS: " + frames);
frames = 0;
}
}
}
Expand Down
17 changes: 3 additions & 14 deletions NewGame/GamePanel.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,8 @@ public class GamePanel extends JPanel {

// controlling speed
private float dirX = 3f;
private float dirY = 3f;;

// fps counter
private int frames = 0;
private long lastCheck = 0;

private float dirY = 3f;

//ball color
private Color color = new Color(24,255,254);

Expand Down Expand Up @@ -50,14 +46,7 @@ public void paintComponent(Graphics g) {

g.setColor(color);
g.fillOval((int)posX, (int)posY, 100, 100);
updateOval();

frames++;
if ((System.currentTimeMillis() - lastCheck) >= 1000) {
lastCheck = System.currentTimeMillis();
System.out.println("FPS: " + frames);
frames = 0;
}
updateOval();
}

private void updateOval() {
Expand Down

0 comments on commit 87a73b0

Please sign in to comment.