我正在关注一个有不同状态要处理的java游戏编程教程。现在我们只是没有对它们做任何事情,只是在我们的主类中实例化它们。定义状态的超类如下:
package com.arjav.tilegame.states;
import java.awt.Graphics;
import com.arjav.tilegame.Game;
public abstract class State {
protected Game game ;
private static State currentState = null ;
public State(Game game) {
this.game = game ;
}
public static void setState(State state){
currentState = state ;
}
public static State getState(){
return currentState ;
}
public abstract void tick();
public abstract void render(Graphics g);
}
我遇到问题的主要课程:
package com.arjav.tilegame;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import com.arjav.tilegame.display.Display;
import com.arjav.tilegame.gfx.Assets;
import com.arjav.tilegame.states.GameState;
import com.arjav.tilegame.states.MenuState;
import com.arjav.tilegame.states.State;
public class Game implements Runnable{
private Display display ;
public int width , height ;
private BufferStrategy bs ;
public String title ;
private Graphics g ;
private boolean running = false ;
private Thread thread ;
//States
private State gameState ;
private State menuState ;
public Game(String title , int width , int height){
this.width = width ;
this.height = height ;
this.title = title ;
}
private void init() {
display = new Display(title , width , height);
Assets.init();
gameState = new State(this);
gameState = new State(this);
State.setState(gameState);
}
private void tick(){
if(State.getState() != null) State.getState().tick();
}
private void render(){
bs = display.getCanvas().getBufferStrategy();
if(bs == null){
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
g.clearRect(0, 0, width, height);
if(State.getState() != null) State.getState().render(g);
bs.show();
g.dispose();
}
public void run() {
init();
int fps = 60 ;
double timePerTick = 1000000000 / fps ;
double delta = 0 ;
long now ;
long lastTime = System.nanoTime();
long timer = 0 ;
int ticks = 0;
while(running){
now = System.nanoTime();;
delta += (now - lastTime) / timePerTick ;
timer += now - lastTime ;
lastTime = now ;
if(delta >= 1){
tick();
render();
ticks++ ;
delta-- ;
}
if(timer >= 1000000000){
System.out.println("Ticks and Frame : " + ticks);
ticks = 0 ;
timer = 0;
}
}
stop();
}
public synchronized void start(){
if(running) return;
running = true ;
thread = new Thread(this);
thread.start();
}
public synchronized void stop(){
if(!running) return ;
running = false ;
try{
thread.join();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
在教程中它很好,但它在这里给出了一些问题D:
答案 0 :(得分:7)
您无法直接创建抽象类的实例。相反,您必须创建一个抽象子类,其中包含每个抽象方法的实现
public class MyState extends State {
MyState(Game g) {
super(g);
}
public void tick() {
System.out.println("tick");
}
public void render(Graphics g) {
System.out.println("I am rendering!");
//render the MyState
}
}
State s = new MyState(myGame);