使用Fisher-Yates Shuffle的随机XML问题

时间:2016-01-20 01:05:29

标签: c# shuffle

我正在制作一个测验/琐事游戏并将问题存储在XML文件中,它会随机提出问题。一切正常,但我希望保持随机,但在每个问题都显示之前不要显示相同的问题。

 public struct Question {
 public string questionText;
 public string answerA;
 public string answerB;
 public string answerC;
 public string answerD;
 public int correctAnswerID;
 }

[XmlRoot("QuestionsRoot")]
public class QuestionData {
[XmlArray("Questions")]
[XmlArrayItem("Question")]
public List<Question>questions = new List<Question>();

 public static QuestionData LoadFromText(string text) {
 try {
     XmlSerializer serializer = new XmlSerializer(typeof(QuestionData));            
     return serializer.Deserialize(new StringReader(text)) as QuestionData;
 } catch (Exception e) {
     UnityEngine.Debug.LogError("Exception loading question data: " + e);
     return null;
 }
}

我在我的另一个脚本中使用它来得到一个随机的问题:

 questionData = QuestionData.LoadFromText(questionDataXMLFile.text)
 q = Random.Range(0, questionData.questions.Count);
 currentQuestion = questionData.questions[q];

1 个答案:

答案 0 :(得分:0)

按照以下几点做一些事情:

创建另一个包含可用问题的列表 - 将其初始化为所有问题列表:

 questionData = QuestionData.LoadFromText(questionDataXMLFile.text)

 var available = new List<Question>(questionData.question);
 ...
 }

 public Question GetNextQuestion()
 {
     if (available.Count == 0)
        available.AddRange(questionData.question);

    q = Random.Range(0, available.Count);
    currentQuestion = available[q];
    available.RemoveAt(q);

    return currentQuestion;
 }