Как закончить вопрос массива, он всегда повторяется - PullRequest
0 голосов
/ 18 марта 2019

Привет всем, мне нужна помощь. У меня есть этот код
У меня 50 строк вопросов, и я хочу, чтобы уже появилось 10 вопросов, после чего игра заканчивается. спасибо за вашу помощь

private Question mQuestion = new Question();

private String mAnswer;
private int mScore = 0;
private int mQuestionLenght = 5 ;

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() == mAnswer){
                mScore++;
                score.setText("Score: " + mScore);
                updateQuestion(r.nextInt(mQuestionLenght));
            } else {
                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(){

}

У меня есть 50 вопросов, которые я хочу, если пользователь уже ответил на 10 вопросов, остановите игру и покажите счет. в этом коде он не может остановиться, если они неправильно ответят, игра может остановиться, но если пользователь всегда прав, игра загрузит все вопросы

Ответы [ 3 ]

1 голос
/ 18 марта 2019

В вашем 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;
}
0 голосов
/ 18 марта 2019

Прежде всего, я бы использовал:

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 и может быть повторным ответом, а сравнение текста не рекомендуется, вы можете использовать объект, который присваивает тексту идентификатор.

Наслаждайтесь кодированием.

0 голосов
/ 18 марта 2019

Добавьте счетчик в ваш код следующим образом:

Int counter = 0;

if(counter <= 10 ){
    updateQuestion(r.nextInt(mQuestionLenght));
    counter++;
} else {
    gameOver();
}

Добавьте это и проверьте, надеюсь, он будет работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...