我一直在用Java,Pong开始我的第一个“游戏”,我觉得我已经准备好实现一个暂停按钮了。使用我当前的代码,按下escape(这意味着使state = State.PAUSE,暂停游戏)会使屏幕闪烁,偶尔会暂停。到目前为止,游戏一直运行良好,所以如果可能的话,我可以尽可能少地更改我的代码。我目前的代码:
运行〜(60 fps:)的main()中的游戏循环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;
}
}
在键盘中,我将所有需要的值分配给布尔值:
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;
}
我的游戏窗口,更新方法:
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;
}
我想知道是否有一种更简单或更简洁的方式来暂停游戏,或者至少在暂停期间停止闪烁(或暂停/取消暂停)。如果我有太多/不够/不干净的代码,我也会事先道歉,绝对不会有任何帮助