我已成功地暫停使用*running = !running
實現暫停/恢復功能
遊戲,但它無法如果這是用來
而且thread.resume()
或thread.wait()
無法正常工作或何時取消暫停取消暫停'P'被按下
private volatile boolean running;
private Thread thread;
public static enum STATE {
MENU,
GAME,
};
public static STATE State = STATE.MENU;
public void init(){
requestFocus();
}
private synchronized void start(){
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private synchronized void stop(){
if(!running)
return;
running = false;
try{
thread.join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
public void run() {
init();
while(running){
/some codes
}
stop();
}
private void render(){
if(State == STATE.GAME){
p.render(g);
c.render(g);
}else if(State == STATE.MENU){
menu.render(g);
}
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(State == STATE.GAME){
if(key == KeyEvent.VK_RIGHT){
p.setVelX(5);
}else if(key == KeyEvent.VK_LEFT){
p.setVelX(-5);
}else if(key == KeyEvent.VK_DOWN){
p.setVelY(5);
}else if(key == KeyEvent.VK_UP){
p.setVelY(-5);
}else if(key == KeyEvent.VK_SPACE && !is_shooting){
c.addEntity(new Bullet(p.getX(), p.getY(), tex, this));
is_shooting = true;
}else if(key == KeyEvent.VK_P){
此行是暫停。
running = !running;
}
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT){
p.setVelX(0);
}else if(key == KeyEvent.VK_LEFT){
p.setVelX(0);
}else if(key == KeyEvent.VK_DOWN){
p.setVelY(0);
}else if(key == KeyEvent.VK_UP){
p.setVelY(0);
}else if(key == KeyEvent.VK_SPACE){
is_shooting = false;
}else if(key == KeyEvent.VK_P){
// This line doesn't work.
running = true;
}
}
你已經打破了循環,運行設置爲true不會重新啓動它。 – Renatols