0

我正在尝试使用 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");
}
4

1 回答 1

0

这是一个开始的活动生命周期的图像,以防您以前没有看过它。我觉得它非常有用:

活动生命周期

你能发布你的游戏板代码吗?错误可能在那里。

也尝试在你的activity_game_play xml中添加你的GameBoard类,就像这个答案中建议的那样:Add class to xml

于 2014-07-23T16:44:38.453 回答