gpt4 book ai didi

java - Java 游戏逻辑的独立线程

转载 作者:行者123 更新时间:2023-12-01 17:38:47 46 4
gpt4 key购买 nike

当我制作简单的单线程游戏时,我以与日益著名的 Space Invaders tutorial 大致相同的方式实现游戏逻辑。如下图所示:

public static void main(String[] args) { //This is the COMPLETE main method
Game game = new Game(); // Creates a new game.
game.gameLogic(); // Starts running game logic.
}

现在我想尝试在单独的线程上运行我的逻辑,但我遇到了问题。我的游戏逻辑位于一个单独的类文件中,如下所示:

public class AddLogic implements Runnable {

public void logic(){
//game logic goes here and repaint() is called at end
}

public void paintComponent(Graphics g){
//paints stuff
}

public void run(){
game.logic(); //I know this isn't right, but I cannot figure out what to put here. Since run() must contain no arguments I don't know how to pass the instance of my game to it neatly.
}

}

...我的主要方法如下所示:

public static void main(String[] args) { //This is the COMPLETE main method
Game game = new Game(); // Creates a new game.
Thread logic = new Thread(new AddLogic(), "logic"); //I don't think this is right either
logic.start();

}

如何在游戏实例上正确调用logic()方法?

最佳答案

您可以使用构造函数或 setter 来传递游戏实例,如

public GameThread extends Thread {
private Game game;

GameThread(Game game) {
this.game = game;
}

public void run() {
game.logic();
}
}

public static void main(String[] args) {
GameThread thread = new GameThread(new Game());
thread.start();
}

关于java - Java 游戏逻辑的独立线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3648684/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com