我正在为移动应用程序类开发 Yahtzee 程序,但遇到了一些麻烦。即使只按下一次 onClick(),我编写的循环也会运行循环(13 圈和 3 卷)。我已将它们移动到几个不同的订单中,但我似乎无法正确处理。有人可以指导我正确的方向,让 onClick 准确地记录转弯和滚动吗?
代码
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class Yahtzee4Activity extends Activity {
/** Called when the activity is first created. */
ImageButton dice1, dice2, dice3, dice4, dice5;
Button roll, begin;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
PlayGame();
}
public void PlayGame()
{
final Random rand = new Random();
final int MAX_TURNS = 13;
final int MAX_ROLLS = 3;
dice1 = (ImageButton)findViewById(R.id.btndice1);
dice2 = (ImageButton)findViewById(R.id.btndice2);
dice3 = (ImageButton)findViewById(R.id.btndice3);
dice4 = (ImageButton)findViewById(R.id.btndice4);
dice5 = (ImageButton)findViewById(R.id.btndice5);
final ImageButton[] dice = {dice1, dice2, dice3, dice4, dice5}; //array of buttons (dice)
final int [] diceValue = new int [5];
final boolean [] isHeld = {false, false, false, false, false}; // array of dice to be held (hold)
roll = (Button)findViewById(R.id.btnroll);
begin = (Button)findViewById(R.id.btnbegin);
roll.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v ) {
RollDice(dice, diceValue, isHeld, rand);
}
});
int turnNum = 0;
for (int i = 0; i < MAX_TURNS; i++) {
int rollNum = 0;
for (int j = 0; j < MAX_ROLLS; j++) {
rollNum++;
roll.setText("Roll (" + (MAX_ROLLS - rollNum) + " Remaining)");
}
turnNum++;
ScoreDice();
}
}
private void ScoreDice() {
// TODO Auto-generated method stub
}
public int[] RollDice(ImageButton [] dice, int [] diceValue, boolean [] isHeld, Random rand)
{
for (int i = 0; i < dice.length; i++) {
if (!isHeld[i]) {
int rndInt = rand.nextInt(6) + 1; // Random number between 1 and 6
String imgName = "die" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
diceValue[i] = rndInt;
dice[i].setImageResource(id); //Loops through the dice array and sets the appropriate dice images based on individual randoms
} else {
//do nothing
}
}
return diceValue;
}
}