我在使用Java实例化一个类时遇到了问题,实际上它会在每个tick中生成一个新世界,这在程序运行时有点令人沮丧。 而我需要做的就是实例化它然后访问类中的变量。
以下是代码:
Background.java
public class Background extends UserView {
private BufferedImage bg;
private static Game game;
public Background(World w, int width, int height) {
super(w, width, height);
try {
bg = ImageIO.read(new File("data/background.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void paintBackground(Graphics2D g) {
super.paintBackground(g);
game = new Game();
g.drawImage(bg, 0, 0, this);
int level = game.getLevel();
g.drawString("Level: " + level, 25, 25);
}
}
Game.java
public Game() {
// make the world
level = 1;
world = new Level1();
world.populate(this);
// make a view
view = new Background(world, 500, 500);
// uncomment this to draw a 1-metre grid over the view
// view.setGridResolution(1);
// display the view in a frame
JFrame frame = new JFrame("Save the Princess");
// quit the application when the game window is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
// display the world in the window
frame.add(view);
// don't let the game window be resized
frame.setResizable(false);
// size the game window to fit the world view
frame.pack();
// make the window visible
frame.setVisible(true);
// get keyboard focus
frame.requestFocus();
// give keyboard focus to the frame whenever the mouse enters the view
view.addMouseListener(new GiveFocus(frame));
controller = new Controller(world.getPlayer());
frame.addKeyListener(controller);
// start!
world.start();
}
/** Run the game. */
public static void main(String[] args) {
new Game();
}
任何帮助将不胜感激!谢谢!
答案 0 :(得分:0)
嗯,你可能需要考虑类概念和它的依赖关系,但这是你最简单,最快速的方法,只保留一个游戏实例:
public class Background extends UserView {
private BufferedImage bg;
private static Game game = new Game();
public Background(World w, int width, int height) {
super(w, width, height);
try {
bg = ImageIO.read(new File("data/background.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void paintBackground(Graphics2D g) {
super.paintBackground(g);
g.drawImage(bg, 0, 0, this);
int level = game.getLevel();
g.drawString("Level: " + level, 25, 25);
}
}
如果您添加更多代码并说出您想要的内容以及您获得的内容,我们可以为您提供更多相关信息。