Skip to content

program console #6

@huyandpeach

Description

@huyandpeach

using System;
using System.Collections.Generic;
using System.Linq;

namespace QuizGame
{
abstract class Question
{
public string Text;

    public Question(string text)
    {
        Text = text;
    }

    public abstract bool Ask();
    public abstract string GetAnswer(); 
}

class MultipleChoice : Question
{
    public string[] Options;
    public int CorrectIndex;

    public MultipleChoice(string text, string[] options, int correctIndex) : base(text)
    {
        Options = options;
        CorrectIndex = correctIndex;
    }

    public override bool Ask()
    {
        Console.WriteLine(Text);
        for (int i = 0; i < Options.Length; i++)
            Console.WriteLine($"{i + 1}. {Options[i]}");

        int input = -1;
        string warning = "";

        while (true)
        {
            Console.Write($"{warning}Your answer (1-4): ");
            string rawInput = Console.ReadLine();

            if (int.TryParse(rawInput, out input) && input >= 1 && input <= Options.Length)
                break;

            Console.SetCursorPosition(0, Console.CursorTop - 1);
            Console.Write(new string(' ', Console.WindowWidth));
            Console.SetCursorPosition(0, Console.CursorTop);
            warning = "⚠ Invalid input. ";
        }

        return input - 1 == CorrectIndex;
    }

    public override string GetAnswer()
    {
        return Options[CorrectIndex];
    }
}

class OpenEnded : Question
{
    public List<string> AcceptableAnswers;

    public OpenEnded(string text, List<string> answers) : base(text)
    {
        AcceptableAnswers = answers.Select(a => a.ToLower().Trim()).ToList();
    }

    public override bool Ask()
    {
        Console.WriteLine(Text);
        Console.Write("Your answer: ");
        string input = Console.ReadLine()?.ToLower().Trim() ?? "";

        while (string.IsNullOrWhiteSpace(input))
        {
            Console.WriteLine("⚠ Answer cannot be empty. Try again.");
            Console.Write("Your answer: ");
            input = Console.ReadLine()?.ToLower().Trim() ?? "";
        }

        return AcceptableAnswers.Contains(input);
    }

    public override string GetAnswer()
    {
        return string.Join(", ", AcceptableAnswers);
    }
}

class TrueFalse : Question
{
    public bool CorrectAnswer;

    public TrueFalse(string text, bool answer) : base(text)
    {
        CorrectAnswer = answer;
    }

    public override bool Ask()
    {
        Console.WriteLine($"{Text} (true/false): ");
        string input = Console.ReadLine()?.ToLower().Trim();

        while (input != "true" && input != "false")
        {
            Console.WriteLine("⚠ Invalid input. Please enter 'true' or 'false'.");
            Console.Write("Your answer (true/false): ");
            input = Console.ReadLine()?.ToLower().Trim();
        }

        return (input == "true" && CorrectAnswer) || (input == "false" && !CorrectAnswer);
    }

    public override string GetAnswer()
    {
        return CorrectAnswer ? "true" : "false";
    }
}


class Program
{
    static List<Question> questions = new List<Question>();

    static void Main()
    {
        while (true)
        {
            Console.Clear();
            Console.WriteLine("=== Geography Quiz Game ===");
            Console.WriteLine("1. Add Question");
            Console.WriteLine("2. Play Quiz");
            Console.WriteLine("3. Show Questions");
            Console.WriteLine("4. Edit Question");
            Console.WriteLine("5. Delete Question");
            Console.WriteLine("6. Exit");
            Console.Write("Choose: ");
            string choice = Console.ReadLine();

            if (choice == "1") AddQuestion();
            else if (choice == "2") PlayQuiz();
            else if (choice == "3") ShowQuestions();
            else if (choice == "4") EditQuestion();
            else if (choice == "5") DeleteQuestion();
            else if (choice == "6") break;
        }
    }

    static void AddQuestion()
    {
        Console.Clear();
        Console.WriteLine("Type? 1. Multiple Choice  2. Open-ended  3. True/False");
        string type = Console.ReadLine();

        Console.Write("Enter question: ");
        string text = Console.ReadLine();

        if (type == "1")
        {
            string[] opts = new string[4];
            for (int i = 0; i < 4; i++)
            {
                Console.Write($"Option {i + 1}: ");
                opts[i] = Console.ReadLine();
            }

            int correct;
            while (true)
            {
                Console.Write("Correct option (1-4): ");
                if (int.TryParse(Console.ReadLine(), out correct) && correct >= 1 && correct <= 4)
                    break;

                Console.WriteLine("⚠ Please enter a number from 1 to 4.");
            }

            questions.Add(new MultipleChoice(text, opts, correct - 1));
        }
        else if (type == "2")
        {
            Console.Write("Enter correct answers (comma separated): ");
            var answers = Console.ReadLine()?.Split(',').ToList() ?? new List<string>();
            questions.Add(new OpenEnded(text, answers));
        }
        else if (type == "3")
        {
            string answer;
            while (true)
            {
                Console.Write("Correct answer (true/false): ");
                answer = Console.ReadLine()?.ToLower().Trim();
                if (answer == "true" || answer == "false")
                    break;

                Console.WriteLine("⚠ Please enter either 'true' or 'false'.");
            }

            bool correct = answer == "true";
            questions.Add(new TrueFalse(text, correct));
        }

        Console.WriteLine("✔ Question added! Press Enter...");
        Console.ReadLine();
    }

    static void ShowQuestions()
    {
        Console.Clear();
        if (questions.Count == 0)
        {
            Console.WriteLine("❗ No questions to show.");
        }
        else
        {
            Console.WriteLine("📄 Current Questions:");
            for (int i = 0; i < questions.Count; i++)
            {
                Console.WriteLine($"{i + 1}. {questions[i].Text}");
            }
        }
        Console.WriteLine("\nPress Enter to return...");
        Console.ReadLine();
    }

    static void EditQuestion()
    {
        if (questions.Count == 0)
        {
            Console.WriteLine("⚠ There are no questions to edit.");
            return;
        }

        ShowQuestions();
        Console.Write("Enter the number of the question to edit: ");
        if (int.TryParse(Console.ReadLine(), out int index) && index >= 1 && index <= questions.Count)
        {
            Question question = questions[index - 1];
            Console.WriteLine($"Current question: {question.Text}");
            Console.Write("Enter new question text (or press Enter to keep current): ");
            string newText = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(newText))
            {
                question.Text = newText;
            }

            if (question is MultipleChoice mcq)
            {
                Console.WriteLine("Do you want to edit the choices? (yes/no): ");
                if (Console.ReadLine().ToLower() == "yes")
                {
                    for (int i = 0; i < mcq.Options.Length; i++)
                    {
                        Console.Write($"Enter new choice {i + 1} (or press Enter to keep '{mcq.Options[i]}'): ");
                        string choice = Console.ReadLine();
                        if (!string.IsNullOrWhiteSpace(choice))
                            mcq.Options[i] = choice;
                    }

                    Console.Write("Enter new correct choice index (1-4): ");
                    if (int.TryParse(Console.ReadLine(), out int correctChoice) && correctChoice >= 1 && correctChoice <= 4)
                    {
                        mcq.CorrectIndex = correctChoice - 1;
                    }
                }
            }
            else if (question is OpenEnded oe)
            {
                Console.WriteLine("Do you want to edit the correct answers? (yes/no): ");
                if (Console.ReadLine().ToLower() == "yes")
                {
                    oe.AcceptableAnswers.Clear();
                    Console.WriteLine("Enter new acceptable answers (type 'done' to finish): ");
                    while (true)
                    {
                        string ans = Console.ReadLine();
                        if (ans.ToLower() == "done")
                            break;
                        if (!string.IsNullOrWhiteSpace(ans))
                            oe.AcceptableAnswers.Add(ans.ToLower());
                    }
                }
            }
            else if (question is TrueFalse tf)
            {
                Console.WriteLine("Do you want to change the correct answer (true/false)? (yes/no): ");
                if (Console.ReadLine().ToLower() == "yes")
                {
                    Console.Write("Enter new correct answer (true/false): ");
                    if (bool.TryParse(Console.ReadLine(), out bool newAnswer))
                    {
                        tf.CorrectAnswer = newAnswer;
                    }
                }
            }

            Console.WriteLine("✅ Question updated.");
        }
        else
        {
            Console.WriteLine("⚠ Invalid question number.");
        }
    }


    static void DeleteQuestion()
    {
        ShowQuestions();
        Console.Write("Enter question number to delete: ");
        if (int.TryParse(Console.ReadLine(), out int index) && index >= 1 && index <= questions.Count)
        {
            questions.RemoveAt(index - 1);
            Console.WriteLine("🗑 Question deleted.");
        }
        else
        {
            Console.WriteLine("⚠ Invalid index.");
        }
        Console.WriteLine("Press Enter to continue...");
        Console.ReadLine();
    }

    static void PlayQuiz()
    {
        if (questions.Count == 0)
        {
            Console.WriteLine("❗ No questions available.");
            Console.ReadLine();
            return;
        }

        int score = 0;
        var start = DateTime.Now;

        foreach (var q in questions)
        {
            Console.Clear();
            Console.WriteLine($"Question {questions.IndexOf(q) + 1}/{questions.Count}\n");

            bool correct = q.Ask();

            if (correct)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("✅ Correct!");
                score++;
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("❌ Incorrect!");
                Console.WriteLine($"👉 Correct Answer: {q.GetAnswer()}");
            }

            Console.ResetColor();
            Console.WriteLine("\nPress Enter to continue...");
            Console.ReadLine();
        }

        var timeTaken = DateTime.Now - start;
        Console.Clear();
        Console.WriteLine($"\n🎉 You scored {score}/{questions.Count}");
        Console.WriteLine($"⏱ Time: {timeTaken.Minutes}m {timeTaken.Seconds}s");

        Console.Write("\nDo you want to see the correct answers for all questions? (yes/no): ");
        string showAnswers = Console.ReadLine().ToLower();
        if (showAnswers == "yes")
        {
            Console.Clear();
            Console.WriteLine("--- 🧠 Correct Answers Recap ---\n");

            int i = 1;
            foreach (var q in questions)
            {
                Console.WriteLine($"Q{i++}: {q.Text}");
                Console.WriteLine($"✅ Answer: {q.GetAnswer()}\n");
            }

            Console.WriteLine("👍 End of answer recap.");
        }

        Console.WriteLine("\nPress Enter to return to the main menu...");
        Console.ReadLine();
    }

}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions