游戏类
private boolean isRunning = false;
private Thread thread;
private Handler handler;
public int hp = 100;
public int ammo = 100;
private Menu menu;
public enum STATE {
Menu,
Game
};
public STATE gameState = STATE.Game;
public Game() {
new Window(800, 600, "Red Ops", this);
start();
handler = new Handler();
menu = new Menu();
if(gameState == STATE.Game) {
handler.addObject(new Player(100, 200, ID.Player, handler));
handler.addObject(new Enemy(500,200, ID.Enemy, handler));
this.addKeyListener(new KeyInput(handler));
}
}
private void start()
{
isRunning = true;
thread = new Thread(this);
thread.start();
}
private void stop()
{
isRunning = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run()
{
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(isRunning) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1) {
tick();
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
frames = 0;
}
}
stop();
}
private void tick()
{
if(gameState == STATE.Game) {
handler.tick();
}else if(gameState == STATE.Menu ) {
menu.tick();
}
}
private void render()
{
BufferStrategy bs = this.getBufferStrategy();
if(bs==null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//////////////////////////////////
g.setColor(Color.red);
g.fillRect(0, 0, 1000, 1000);
if(gameState == STATE.Game) {
g.setColor(Color.gray);
g.fillRect(5,5,200,32);
g.setColor(Color.green);
g.fillRect(5,5,hp*2,32);
g.setColor(Color.black);
g.drawRect(5,5,200,32);
g.setColor(Color.white);
g.drawString("Ammo: " + ammo, 5,50);
}else if(gameState == STATE.Menu) {
menu.render(g);
/////////////////////////////////
handler.render(g);
g.dispose();
bs.show();
}
}
public static void main(String args[])
{
new Window(800,600,"Red Ops",new Game());
}
}
菜单类
private Game game;
private Handler handler;
private Game menu;
public Menu(Game game, Handler handler) {
this.game = game;
this.handler = handler;
}
public void tick(){
}
公共无效渲染(图形g){
``if(game.gameState == STATE.Menu) {
`` g.setColor(Color.RED);
` `g.drawRect(100,100,150,60);
}
}
}
我正在尝试从菜单类向游戏类调用render方法,但是不断出现定义菜单类的tick和render方法所需的错误。
先谢谢了:)