在简单的数学游戏中添加高分

时间:2019-03-13 10:09:07

标签: java

我正在制作一个简单的数学游戏,其中包含20个加,减和乘的问题。我正在尝试添加高分功能,该功能将在分数的最后显示,以显示用户是否超过了高分,以及他们是否没有当前的高分。

以下是我到目前为止用于游戏的代码。

package au.edu.usc.mathgame;

import java.util.Random;
import java.util.Scanner;

/**
 * A simple console-based maths quiz for primary school children.
 *
 *
public class Main {

public static void main(String[] args) {
    Random rand = new Random();
    Scanner input = new Scanner(System.in);

    int score = 0;

    // now ask some random addition questions.
    for (int i = 0; i < 10; i++) {
        int a = rand.nextInt(20);
        int b = rand.nextInt(20);
        int questionType = rand.nextInt(3);
        Question q = new Question(a, b, questionType);
        q.showQuestion();


     // Code to print test results
        int response = input.nextInt();
        boolean result = q.checkAnswer(response);
        if (result) {
            score = score + 1;
        }

    }
    System.out.printf("Your Total Score is %2d ",score);
}
}

package au.edu.usc.mathgame;

import java.util.Random;

public class Question {
private int value1;
private int value2;
private int answer;
private int questionType;
private String operator;

public Question(int a, int b, int questionType) {
    value1 = a;
    value2 = b;

    Random rand = new Random();


    // Sets the operator based on the question type and calculates the answer

    if (questionType == 0) {
        operator = "+";
        answer = a + b;
    }
    else if (questionType == 1) {
        operator = "-";
        answer = a - b;
    }
    else if (questionType == 2) {
        operator = "*";
        answer = a * b;
    }

}

/**
 * Selects operator and prints question.
 *
 *
*/
public void showQuestion() {

    System.out.printf("What is %2d %s %2d? ", value1, operator, value2);
}

// checks and prints answers

public boolean checkAnswer(int response) {
    if (response == answer) {
        System.out.printf("  Yes!\n");
        return true;
    } else {
        System.out.printf("  No, the answer is %d.\n", answer);
        return false;
    }

}

} 这是一个非常简单的游戏,我只想添加一个高分功能

1 个答案:

答案 0 :(得分:0)

您可以维护包含高分的文本文件。每当游戏结束时,您都应该阅读该文件并将其与当前玩家得分进行比较。如果它低于最高分数,则在屏幕上显示最高分数,否则用当前播放器分数替换文件中的值。

有关如何使用Java读写文件,您可以参考以下链接:

Java - Files and I/O