/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.Random;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
App.main(args);
}
}
class App {
// Инициализируем App и запускаем Start()
public static void main(String[] args){
App app = new App();
app.Start();
}
// Некоторые константы:
final String sucAns = "Good job!";
final String wrongAns = "Wrong... Try again next time!";
public ArrayList<Engine> games = new ArrayList<Engine>();
public void Start(){
Scanner in = new Scanner(System.in);
games.add(new Calculator());
// Выводим список игр и их индекс+1 (что бы отсчёт начинался с 1)
System.out.println("Please select game: ");
for (int i = 0; i < games.size(); i++){
System.out.println((i+1) + " - " + games.get(i).GetName());
}
System.out.println("0 - Exit");
int gameIndex = in.nextInt();
if (gameIndex == 0) {return;}
// Так как отсчёт игр начинался с одного
// Вычитаем единицу
Engine game = games.get(gameIndex-1);
// Выводим название и описание игры
System.out.println(game.GetName());
System.out.println(game.GetDescription());
// Генерируем вопрос
game.GenerateQuestion();
// Выводим вопрос
System.out.println("Question: " + game.GetQuestion());
// Запрашиваем ответ от пользователя
String ans = in.next();
// Проверяем, правильный ли ответ
boolean isCorrect = game.IsAnswerCorrect(ans);
if (isCorrect) { System.out.println(sucAns); }
else { System.out.println(wrongAns); }
}
}
// Так как Engine является лишь базовым классом
// сделаем его абстрактным, что бы его нельзя было создавать
abstract class Engine {
// Имя игры (по умолчанию - имя класса)
public String GetName() {return this.getClass().getSimpleName();}
// Описание игры
public abstract String GetDescription();
// Генерация и сохранение вопроса и ответа
public abstract void GenerateQuestion();
public abstract String GetQuestion();
public abstract boolean IsAnswerCorrect(String answer);
// Рандом (на всякий случай)
final Random random = new Random();
}
class Calculator extends Engine {
@Override
public String GetDescription() {
return "This is a calculator game. I'm write mathematical example and you provide answer.";
}
int num1 = 0;
int num2 = 0;
@Override
public void GenerateQuestion(){
num1 = random.nextInt(10);
num2 = random.nextInt(10);
}
@Override
public String GetQuestion(){
return num1 + " + " + num2 + " = ";
}
@Override
public boolean IsAnswerCorrect(String answer){
return answer.equals(Integer.toString(num1 + num2));
}
}