Skip to content

form1 #4

@tranlongcbvn112-sketch

Description

@tranlongcbvn112-sketch

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GeographyQuizWinForms
{
public partial class Form1 : Form
{
private QuestionManager manager = new QuestionManager();

    public Form1()
    {
        InitializeComponent();
        AIQuestionBank.LoadFromFile();
        lblFeedback.Text = "";
        PopulateAIList();
    }

    private void SetPlaceholder(TextBox txt, string placeholder)
    {
        txt.Text = placeholder;
        txt.ForeColor = Color.Gray;

        txt.GotFocus += (s, e) =>
        {
            if (txt.Text == placeholder)
            {
                txt.Text = "";
                txt.ForeColor = Color.Black;
            }
        };

        txt.LostFocus += (s, e) =>
        {
            if (string.IsNullOrWhiteSpace(txt.Text))
            {
                txt.Text = placeholder;
                txt.ForeColor = Color.Gray;
            }
        };
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        SetPlaceholder(txtOpt1, "Option 1");
        SetPlaceholder(txtOpt2, "Option 2");
        SetPlaceholder(txtOpt3, "Option 3");
        SetPlaceholder(txtOpt4, "Option 4");
        SetPlaceholder(txtAccepted, "Comma-separated answers");
    }

    private void PopulateAIList()
    {
        questionListBox.DataSource = null;
        var list = AIQuestionBank.Questions
            .Select((line, index) =>
            {
                var q = manager.ConvertAIToQuestion(line);
                return q != null ? $"{index + 1}. {q.QuestionText}" : $"{index + 1}. [Invalid]";
            }).ToList();
        questionListBox.DataSource = list;
    }

    // ==== Quản lý câu hỏi ====
    private void btnAdd_Click(object sender, EventArgs e)
    {
        string type = cmbType.SelectedItem?.ToString() ?? "";
        string questionText = txtQuestion.Text.Trim();

        if (string.IsNullOrWhiteSpace(type) || string.IsNullOrWhiteSpace(questionText))
        {
            lblFeedback.Text = "❌ Please select type and enter question text.";
            lblFeedback.ForeColor = Color.Red;
            return;
        }

        if (type == "Multiple Choice")
        {
            if (string.IsNullOrWhiteSpace(txtOpt1.Text) ||
                string.IsNullOrWhiteSpace(txtOpt2.Text) ||
                string.IsNullOrWhiteSpace(txtOpt3.Text) ||
                string.IsNullOrWhiteSpace(txtOpt4.Text) ||
                cmbCorrect.SelectedIndex < 0)
            {
                lblFeedback.Text = "❌ Please fill all options and choose correct answer.";
                lblFeedback.ForeColor = Color.Red;
                return;
            }
        }
        else if (type == "True/False")
        {
            if (!rTrue.Checked && !rFalse.Checked)
            {
                lblFeedback.Text = "❌ Please select True or False.";
                lblFeedback.ForeColor = Color.Red;
                return;
            }
        }
        else if (type == "Open Ended")
        {
            if (string.IsNullOrWhiteSpace(txtAccepted.Text))
            {
                lblFeedback.Text = "❌ Please enter accepted answers.";
                lblFeedback.ForeColor = Color.Red;
                return;
            }
        }

        if (type == "Multiple Choice")
        {
            string[] options = { txtOpt1.Text, txtOpt2.Text, txtOpt3.Text, txtOpt4.Text };
            int correctIndex = cmbCorrect.SelectedIndex;
            manager.AddQuestionFromUI("mcq", questionText, options, correctIndex, null, null);
        }
        else if (type == "True/False")
        {
            bool isTrue = rTrue.Checked;
            manager.AddQuestionFromUI("tf", questionText, null, 0, null, isTrue);
        }
        else if (type == "Open Ended")
        {
            string[] answers = txtAccepted.Text.Split(',').Select(x => x.Trim()).ToArray();
            manager.AddQuestionFromUI("open", questionText, null, 0, answers, null);
        }

        lblFeedback.Text = "✅ Added successfully.";
        lblFeedback.ForeColor = Color.Green;
        PopulateAIList();
    }

    private void btnEdit_Click(object sender, EventArgs e)
    {
        int idx = questionListBox.SelectedIndex;
        if (idx < 0)
        {
            lblFeedback.Text = "Please select a question to edit.";
            lblFeedback.ForeColor = Color.Red;
            return;
        }

        string type = cmbType.SelectedItem?.ToString() ?? "";
        string questionText = txtQuestion.Text.Trim();

        if (string.IsNullOrWhiteSpace(type) || string.IsNullOrWhiteSpace(questionText))
        {
            lblFeedback.Text = "❌ Please select type and enter question text.";
            lblFeedback.ForeColor = Color.Red;
            return;
        }

        string formatted = "";
        if (type == "Multiple Choice")
        {
            if (string.IsNullOrWhiteSpace(txtOpt1.Text) ||
                string.IsNullOrWhiteSpace(txtOpt2.Text) ||
                string.IsNullOrWhiteSpace(txtOpt3.Text) ||
                string.IsNullOrWhiteSpace(txtOpt4.Text) ||
                cmbCorrect.SelectedIndex < 0)
            {
                lblFeedback.Text = "❌ Please fill all options and choose correct answer.";
                lblFeedback.ForeColor = Color.Red;
                return;
            }
            string[] options = { txtOpt1.Text, txtOpt2.Text, txtOpt3.Text, txtOpt4.Text };
            formatted = manager.FormatAsAIEntry(new MultipleChoiceQuestion
            {
                QuestionText = questionText,
                Options = options,
                CorrectOption = cmbCorrect.SelectedIndex
            });
        }
        else if (type == "True/False")
        {
            if (!rTrue.Checked && !rFalse.Checked)
            {
                lblFeedback.Text = "❌ Please select True or False.";
                lblFeedback.ForeColor = Color.Red;
                return;
            }
            formatted = manager.FormatAsAIEntry(new TrueFalseQuestion
            {
                QuestionText = questionText,
                IsTrue = rTrue.Checked
            });
        }
        else if (type == "Open Ended")
        {
            if (string.IsNullOrWhiteSpace(txtAccepted.Text))
            {
                lblFeedback.Text = "❌ Please enter accepted answers.";
                lblFeedback.ForeColor = Color.Red;
                return;
            }
            formatted = manager.FormatAsAIEntry(new OpenEndedQuestion
            {
                QuestionText = questionText,
                AcceptedAnswers = txtAccepted.Text.Split(',').Select(a => a.Trim()).ToList()
            });
        }

        AIQuestionBank.Questions[idx] = formatted;

        lblFeedback.Text = "✅ Question updated successfully.";
        lblFeedback.ForeColor = Color.Green;
        PopulateAIList();
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        int idx = questionListBox.SelectedIndex;
        if (idx < 0)
        {
            lblFeedback.Text = "Please select a question to delete.";
            lblFeedback.ForeColor = Color.Red;
            return;
        }

        AIQuestionBank.Questions.RemoveAt(idx);
        lblFeedback.Text = "Deleted successfully.";
        lblFeedback.ForeColor = Color.Green;
        PopulateAIList();
    }

    // ==== Chơi Quiz ====
    private void btnStartQuiz_Click(object sender, EventArgs e)
    {
        string targetType = rbMCQ.Checked ? "mcq" :
                            rbTrueFalse.Checked ? "tf" : "open";

        manager.ClearSummary();
        manager.StartQuiz(targetType, 5);
        if (manager.GetTotalQuestions() == 0)
        {
            lblAnswerFeedback.ForeColor = Color.Red;
            lblAnswerFeedback.Text = "❌ No questions available.";
            return;
        }

        ShowQuestion(manager.GetCurrentQuestion());
        lblYourAnswer.Text = "Your Answer: \nCorrect Answer: ";

        lblScoreOutside.Text = $"Score: {manager.GetScore()} / {manager.GetTotalQuestions()}";
        lblScore.Text = "";
        tabControl1.SelectedTab = tabQuiz;
        btnStartQuiz.Enabled = false;
    }

    private void btnNext_Click(object sender, EventArgs e)
    {
        Question currentQuestion = manager.GetCurrentQuestion();
        if (currentQuestion == null) return;

        string userAnswer = GetUserAnswer(currentQuestion);
        bool isCorrect = manager.SubmitAnswer(userAnswer);
        manager.SaveAnswerSummary(currentQuestion, userAnswer, isCorrect);

        lblAnswerFeedback.ForeColor = isCorrect ? Color.Green : Color.Red;
        lblAnswerFeedback.Text = isCorrect ? "✅ Correct!" : "❌ Incorrect!";
        lblYourAnswer.Text = $"Your Answer: {userAnswer}\nCorrect Answer: {currentQuestion.GetCorrectAnswer()}";
        lblScoreOutside.Text = $"Score: {manager.GetScore()} / {manager.GetTotalQuestions()}";

        if (manager.HasNextQuestion())
        {
            ShowQuestion(manager.GetCurrentQuestion());
        }
        else
        {
            lblAnswerFeedback.ForeColor = Color.Blue;
            lblAnswerFeedback.Text = "🎉 Quiz finished!";
            btnStartQuiz.Enabled = true;

            
            StringBuilder summary = new StringBuilder("===== Quiz Summary =====\n");
            
            lstSummary.Items.Clear();
            foreach (var s in manager.Summary)
            {
                lstSummary.Items.Add($"Q: {s.Question}");
                lstSummary.Items.Add($"Your Answer: {s.YourAnswer}");
                lstSummary.Items.Add($"Correct: {s.CorrectAnswer}");
                lstSummary.Items.Add($"Result: {(s.IsCorrect ? "Correct" : "Incorrect")}");
                lstSummary.Items.Add("-----------------------------------");
            }


        }
    }

    private string GetUserAnswer(Question currentQuestion)
    {
        if (currentQuestion is MultipleChoiceQuestion)
        {
            if (opt1_Quiz.Checked) return opt1_Quiz.Text;
            if (opt2_Quiz.Checked) return opt2_Quiz.Text;
            if (opt3_Quiz.Checked) return opt3_Quiz.Text;
            if (opt4_Quiz.Checked) return opt4_Quiz.Text;
        }
        else if (currentQuestion is TrueFalseQuestion)
        {
            if (opt1_Quiz.Checked) return "True";
            if (opt2_Quiz.Checked) return "False";
        }
        else if (currentQuestion is OpenEndedQuestion)
        {
            return txtAnswer_Quiz.Text.Trim();
        }
        return string.Empty;
    }

    private void ShowQuestion(Question q)
    {
        q.RenderToUI(lblQuestion_Quiz,
                     new[] { opt1_Quiz, opt2_Quiz, opt3_Quiz, opt4_Quiz },
                     txtAnswer_Quiz);

        lblAnswerFeedback.Text = "";
    }

    private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
    {
        string type = cmbType.SelectedItem?.ToString() ?? "";
        grpMCQ.Enabled = false;
        grpTrueFalse.Enabled = false;
        grpOpen.Enabled = false;

        if (type == "Multiple Choice") grpMCQ.Enabled = true;
        else if (type == "True/False") grpTrueFalse.Enabled = true;
        else if (type == "Open Ended") grpOpen.Enabled = true;
    }

    private void lblYourAnswer_Click(object sender, EventArgs e)
    {

    }
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions