3 回答
TA贡献1794条经验 获得超8个赞
在 Acitivty 中,添加计数器属性
private int numberOfQuestionsAsked = 0;
在提出每个问题后,将1添加到您的计数器
if(answer4.getText().equals(mAnswer)){ //note : use .equals() and not == !
mScore++;
numberOfQuestionsAsked++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mQuestionLenght));
}
用户回答问题后,检查计数器是否达到10,如果是,请转到gameOver
if(numberOfQuestionsAsked <= 10) {
gameOver();
}
在gameOver中,重置计数器,以便游戏可以重新启动
numberOfQuestionsAsked = 0;
您的代码应如下所示
private Question mQuestion = new Question();
private String mAnswer;
private int mScore = 0;
private int mQuestionLenght = 5 ;
private int numberOfQuestionsAsked = 0;
Random r;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
r = new Random();
answer1 = (Button) findViewById(R.id.answer1);
answer2 = (Button) findViewById(R.id.answer2);
answer3 = (Button) findViewById(R.id.answer3);
answer4 = (Button) findViewById(R.id.answer4);
score = (TextView) findViewById(R.id.score);
question = (TextView) findViewById(R.id.question);
score.setText("Score: " + mScore );
updateQuestion(r.nextInt(mQuestionLenght));
answer4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(answer4.getText().equals(mAnswer)){ //note : use .equals() and not == !
mScore++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mQuestionLenght));
numberOfQuestionsAsked++;
} else {
gameOver();
}
if(numberOfQuestionsAsked <= 10) {
gameOver();
}
}
});
}
private void updateQuestion(int num){
question.setText(mQuestion.getQuestion(num));
answer1.setText(mQuestion.getChoice1(num));
answer2.setText(mQuestion.getChoice2(num));
answer3.setText(mQuestion.getChoice3(num));
answer4.setText(mQuestion.getChoice4(num));
mAnswer = mQuestion.getCorrectAnswer(num);
}
private void gameOver(){
numberOfQuestionsAsked = 0;
}
TA贡献1909条经验 获得超7个赞
首先,我会使用:
View.OnClickListener listener = new View.onClickListener() {
@Override
public void onClick(View view) {
if(view instanceOf (TextView) && ((TextView)view).getText().toString().equals(mAnswer)){
mScore++;
score.setText("Score: " + mScore);
if(mScore >= 10) {
gameCompleted();//ToDo
} else {
updateQuestion(r.nextInt(mQuestionLenght));
}
} else {
gameOver();
}
}
};
然后,在每个答案中使用此侦听器。此外,您的随机数可能会失败,因为它可能高于50,并且可以是重复的答案,并且不建议使用文本比较,您可以使用为文本分配ID的对象。
享受编码。
TA贡献1884条经验 获得超4个赞
在代码中添加一个计数器,如下所示:
整型计数器 = 0;
if(counter <= 10 ){
updateQuestion(r.nextInt(mQuestionLenght));
counter++;
} else {
gameOver();
}
添加此内容并检查,希望它能正常工作。
添加回答
举报