所以,我开始为游戏编写代码,这次我想为启动器和游戏使用单独的类。 所以基本上它是一个单线程游戏,并且线程是在启动器中制作并启动的,而Game类是" Runnable"用run方法。 问题是即使我启动线程,run方法也不会被调用。
启动器:
public class Launcher {
private Thread thread;
private static Game game;
public static void main(String[] args) {
Launcher obj = new Launcher();
game = new Game();
obj.start();
}
public synchronized void start() {
if(game.running) return;
game.running = true;
thread = new Thread(game);
thread.start();
}
public synchronized void stop() {
if(!game.running) return;
game.running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
游戏课程:
public class Game extends JFrame implements Runnable{
public boolean running = false;
private static int WIDTH = 1280 , HEIGHT = 720;
private Screen screen;
public Game() {
this.setTitle("Game");
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.running = true;
this.setVisible(true);
init();
}
public void init() {
screen = new Screen(WIDTH, HEIGHT);
this.add(screen);
screen.init();
this.pack();
}
public void render() {
Screen.clearScreen();
Screen.update();
}
public void update() {
}
@Override
public void run() {
System.out.println("called"); //Checking if it was called, and it is not being called
long lastTime = System.nanoTime();
long now;
int fps = 60;
double timePerTick = 1000000000/fps;
double delta = 0;
while(running) {
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
lastTime = now;
if(delta >= 1){
update();
delta--;
}
render();
}
}
}
答案 0 :(得分:3)
创建new Game()
时,设置running = true
。稍后你会在你的发射器if(game.running) return
中检查它是否为真,然后返回。
无关: 支持封装不要像运行那样暴露公共字段。只是公开一些方法,告诉你这些信息,如:
public class Game{
private boolean running;
...
public boolean isRunning(){
return running;
}
}
答案 1 :(得分:1)
在此构造函数中
public Game() {
this.setTitle("Game");
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.running = true;
this.setVisible(true);
init();
}
您必须设置this.running = false;
才能启动游戏主题。
答案 2 :(得分:0)
创建游戏时,将if expression1:
statement(s)
elif expression2:
statement(s)
else:
statement(s)
设置为true:
running
当你打电话给start时,你会检查它是否已经在运行,如果是,你会提前返回:
public Game() {
//...
this.running = true;
所以你总是在做任何事情之前退出这个方法。