我正在尝试使用java构建android游戏(这是我第一次这样做,所以我很新)。当用户从主活动中选择他们想玩的游戏时,GamePlay活动类被调用。在这个类中,我试图加载我创建的GameBoard视图,然后运行一个循环,在游戏结束时结束。我已经尝试了一些不同的方法来做到这一点(包括线程),但我遇到的问题是,在进入循环之前视图不加载。我最终会得到一个黑屏和一个无限循环。有什么建议吗?
注意:单板有点击检测,成功赋值d1和d2。
public class GamePlay extends Activity{
private Player P1;
private Player P2;
private GameBoard board;
private Player turn;
private boolean gameOver = false;
private Thread thread;
//Variables associated with turn
private Dot d1 = null;
private Dot d2 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_play);
Bundle extra = getIntent().getExtras();
String type = extra.getString("GAME_TYPE");
//Set up appropriate players
if (type.equals(StartDB.ONE_PLAYER)){
this.setTitle("One Player Dots And Boxes");
String P1Name = "Person";
P1 = new HumanPlayer(Color.RED, P1Name);
P2 = new AIPlayer(Color.BLUE, "Computer");
} else {
this.setTitle("Two Player Dots And Boxes");
String P1Name = "Player 1";
String P2Name = "Player 2";
P1 = new HumanPlayer(Color.RED, P1Name);
P2 = new HumanPlayer(Color.BLUE, P2Name);
}
//Initialize turn to first player
setTurn(P1);
//Set up a game board
board = new GameBoard(this, this);
setContentView(board);
}
@Override
protected void onStart() {
super.onStart();
//Create turn thread and run it
while (!gameOver){
while(d2 == null){
try {
Thread.sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println("Making a line");
Line line = new Line(d1, d2);
board.addLine(line);
d1 = null;
d2 = null;
board.invalidate();
//This was another attempt made:
//try {
//thread = new Thread(new GameLoop(this));
//thread.start();
//thread.join();
//} catch (InterruptedException e) {
//e.printStackTrace();
//}
checkGameOver();
}
System.out.println("Game Over");
}
这是一个活动生命周期的图像,以防你以前没有见过它。我发现它很有用:
活动生命周期
你能张贴你的游戏板代码吗?错误可能在这里。
也尝试在你的activity_game_play xml中添加你的GameBoard类,就像在这个答案中建议的那样:添加类到xml