2012年6月13日 星期三

Java Game Development(26) - Intro to Keyboard Input


import java.awt.*;
import javax.swing.*;


public abstract class Core {
private static DisplayMode modes[] = {
new DisplayMode(800,600,32,0),
new DisplayMode(800,600,24,0),
new DisplayMode(800,600,16,0),
new DisplayMode(640,480,32,0),
new DisplayMode(640,480,24,0),
new DisplayMode(640,480,16,0),
};
private boolean running;
protected ScreenManager s;
//停止運行
public void stop(){
running = false;
}
//調用INITgameloop
public void run(){
try{
init();
gameloop();
}finally{
s.restoreScreen();
}
}
//設置全屏
public void init() {
s = new ScreenManager();
DisplayMode dm = s.findFirstCompatibleMode(modes);
s.setFullScreen(dm);

Window w = s.getFullScreenWindow();
w.setFont(new Font("Arial", Font.PLAIN, 20));
w.setBackground(Color.GREEN);
w.setForeground(Color.WHITE);
running = true;
}

//主遊戲循環
public void gameloop() {
long startTime = System.currentTimeMillis();
long cumTime = startTime;

while (running) {
long timePassed = System.currentTimeMillis() - cumTime;
cumTime += timePassed;

update(timePassed);
Graphics2D g = s.getGraphics();
draw(g);
g.dispose();
s.update();

try {
Thread.sleep(20);
} catch (Exception ex) {}
}
}

//更新動畫
public void update(long timePassed) {
}

//繪製到屏幕上
public abstract void draw(Graphics2D g);


}


創建新class(KeyTest.java)




import java.awt.*;
import java.awt.event.*;


public class KeyTest extends Core implements KeyListener { 是從鍵盤的監聽器
public static void main(String[] args) {
new KeyTest().run();
}
private String mess = "";
//init also call init from super class
public void init() {
super.init(); 調用init()(core java)
Window w = s.getFullScreenWindow();
w.setFocusTraversalKeysEnabled(false); 鍵盤設置普通按鈕
w.addKeyListener(this); 等待鍵盤輸入
mess = "Press escape to exit";
}

}

沒有留言:

張貼留言