所以我有一个运行简单的蛇和梯子游戏的活动,我想让玩家点击一个按钮并移动,随后计算机移动。我的问题是,一旦玩家移动,计算机就会立即移动。
相反,我希望活动在计算机移动之前等待。我环顾四周,发现等待涉及使用线程,但我未能在我的应用程序崩溃的情况下实现它
我尝试声明一个线程:
final Runnable runnable = new Runnable() {
@Override
public void run()
{
while (true)
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
Thread thread= new Thread(runnable);
我的按钮的 onClick() 方法:
Button rollButton = (Button) (findViewById(R.id.rollButton));
rollButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//executes only if current player is a human
if(GAME_BOARD.getCurrentPlayer().isHuman()) {
GAME_BOARD.rollDie(); // rolls the die
showDie(GAME_BOARD); // displays die on screen
GAME_BOARD.move(); // moves the player and sets next player as current player
playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");// sets TextView to display who's player's turn it is
thread.start();
if(!GAME_BOARD.getCurrentPlayer().isHuman()) {
GAME_BOARD.rollDie();
showDie(GAME_BOARD);
GAME_BOARD.move();
playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");
}
}
}
});
再说一次,我的问题是,我该如何做到,以便在第二个 if 语句执行之前,活动等待,比如 4 秒?