using UnityEngine; using System.Collections.Generic; using System.Linq; public class QuestionManager : MonoBehaviour { private List allQuestions; private List currentQuestions; private int currentQuestionIndex = 0; void Start() { LoadQuestions(); ShuffleQuestions(); GenerateWrongAnswers(); } void LoadQuestions() { Debug.Log("开始加载题目"); TextAsset jsonFile = Resources.Load("multiplication_table"); if (jsonFile != null) { Debug.Log("JSON文件加载成功:" + jsonFile.text); // 直接将 JSON 数组包装在一个对象中 QuestionDataList questionList = JsonUtility.FromJson("{\"questions\":" + jsonFile.text + "}"); if (questionList != null && questionList.questions != null && questionList.questions.Length > 0) { allQuestions = new List(questionList.questions); currentQuestions = new List(allQuestions); Debug.Log($"成功加载 {currentQuestions.Count} 道题目"); // 打印第一道题目以验证 if (currentQuestions.Count > 0) { var firstQ = currentQuestions[0]; Debug.Log($"第一道题目: {firstQ.multiplier1} × {firstQ.multiplier2} = {firstQ.result}"); } } else { Debug.LogError("JSON解析失败!questionList 为空或没有题目"); } } else { Debug.LogError("无法加载题目文件!请确保 multiplication_table.json 文件位于 Resources 文件夹中!"); } } void GenerateWrongAnswers() { foreach (var question in currentQuestions) { // 生成一个错误答案,确保与正确答案不同 do { // 在正确答案的±5范围内生成错误答案 int offset = Random.Range(-5, 6); question.wrongAnswer = question.result + offset; } while (question.wrongAnswer == question.result); // 随机决定正确答案放在A还是B选项 question.isAnswerA = Random.value > 0.5f; } } void ShuffleQuestions() { if (currentQuestions != null) { int n = currentQuestions.Count; while (n > 1) { n--; int k = Random.Range(0, n + 1); QuestionData temp = currentQuestions[k]; currentQuestions[k] = currentQuestions[n]; currentQuestions[n] = temp; } } } public QuestionData GetCurrentQuestion() { if (currentQuestions != null && currentQuestionIndex < currentQuestions.Count) { return currentQuestions[currentQuestionIndex]; } return null; } public bool CheckAnswer(bool selectedA) { QuestionData currentQuestion = GetCurrentQuestion(); if (currentQuestion != null) { return selectedA == currentQuestion.isAnswerA; } return false; } public void NextQuestion() { currentQuestionIndex++; if (currentQuestionIndex >= currentQuestions.Count) { // 所有题目都已完成,重新开始 currentQuestionIndex = 0; ShuffleQuestions(); GenerateWrongAnswers(); } } public float GetProgress() { return (float)currentQuestionIndex / currentQuestions.Count; } }