I've been working on my first "game" in Java, Pong, and I feel as if I'm ready to implement a pause button. With my current code, pressing escape (which is meant to make state = State.PAUSE, pausing the game) makes the screen flicker, and occasionally pause. The game has been running well until so far, so it'd be preferable if I could change my code as little as possible, if possible. My current code:
gameloop in main() running ~60 fps:
int fps = 60;
double timePerTick = 1000000000 / fps;
double delta = 0;
long now;
long lastTime = System.nanoTime();
while (true) {
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
timer += now - lastTime;
lastTime = now;
if(delta >= 1){
//refreshes Keyboard
p.key.nUpdate();
//refreshes game
p.nUpdate();
//refreshes graphics
p.nPaint();
ticks++;
delta--;
}
if(timer >= 1000000000){
log();
ticks = 0;
timer = 0;
}
}
in Keyboard, I assign all needed values to booleans:
public class Keyboard extends KeyAdapter implements KeyListener {
private boolean[] keys;
public boolean escape;
public boolean r;
public Keyboard(){
keys = new boolean[256];
}
public void nUpdate(){
escape = keys[KeyEvent.VK_ESCAPE];
r = keys[KeyEvent.VK_R];
}
@Override
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
@Override
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
my game window, update methods:
public void nUpdate() {
if (key.r) newMatch();
if (key.escape) pause();
if (state == State.GAME) {...}
}
public void paint(Graphics g) {
switch (state) {
case GAME: ...
case PAUSE: ...
}
public void nPaint() {
repaint();
}
public void pause() {
if (state == State.GAME) state = State.PAUSE;
else if (state == State.PAUSE) state = State.GAME;
}
I'm wondering if there is a simpler or cleaner way to pause the game, or at least stop it from flickering during pause (or being paused/unpaused repeatedly). I also apologize in advance if I have too much/not enough/unclean code, absolutely any help is appreciated