//********************* // create by 流云 // time: 2025.4.10 // desc: 答题模块 //********************* import { game } from "cc"; /** * 答题模块 */ export class AnswerQuestions { /** * 选择事件 */ static readonly EVENT_SELECT = "AnswerQuestions.EVENT_SELECT"; /** * 一组答题结束事件 */ static readonly EVENT_END = "AnswerQuestions.EVENT_END"; /** * 问题 */ Questions: Question[] = []; /** * 当前 */ Curent: Question = null; /** * 是否自动下一个 */ private _autoNext: boolean = false; /** * 初始化 */ init(Questions: Question[], autoNext: boolean = false) { this.Questions = Questions; this._autoNext = autoNext; this.Curent = null; } /** * 下一个 */ next() { let index = this.Questions.indexOf(this.Curent); if (index < this.Questions.length - 1) { this.Curent = this.Questions[index + 1]; } else { this.Curent = null; game.emit(AnswerQuestions.EVENT_END); } } /** * 选择 * @param questionStr 问题 * @param selectItemStr 选项 */ select(questionStr: string, selectItemStr: string) { let question = this.Questions.find((item) => { return item.Question == questionStr }); if (question && question.Options.indexOf(selectItemStr) >= 0) { // 如果是单选,则清空已选 if (question.IsRadio) { question.SelectOptions = []; } let index = question.SelectOptions.indexOf(selectItemStr); if (index >= 0) { question.SelectOptions.splice(index, 1); } else if (question.SelectOptions.length < question.Answer.length) { question.SelectOptions.push(selectItemStr); } game.emit(AnswerQuestions.EVENT_SELECT, question); if (question.IsFinishSelect && this._autoNext) { this.next(); } } } /** * 验证所有题目是否完成 * @returns 是否完成 */ checkAllFinish() { return this.Questions.every((item) => { return item.IsFinishSelect }); } /** * 验证所有题目是否正确 * @returns 是否正确 */ checkAllRight() { return this.Questions.every((item) => { return item.IsRight }); } /** * 获取完成题目数量 * @returns 完成题目数量 */ getFinshCount() { return this.Questions.filter((item) => { return item.IsFinishSelect }).length; } /** * 获取所有题目数量 * @returns 有题目数量 */ getTotalCount() { return this.Questions.length; } /** * 获取正确题目数量 * @returns 正确题目数量 */ getRightCount() { return this.Questions.filter((item) => { return item.IsRight }).length; } /** * 重置 */ reset(question: string) { let q = this.Questions.find((item) => { return item.Question == question }); if (q) { q.SelectOptions = []; } } /** * 重置所有 */ resetAll() { this.Questions.forEach((item) => { item.SelectOptions = [] }); } } /** * 问题 */ export class Question { /** * 组名 */ GroupName: string = ""; /** * 问题 */ Question: string = ""; /** * 答案 */ Answer: string[] = []; /** * 选项 */ Options: string[] = []; /** * 已选 */ SelectOptions: string[] = []; /** * 是否完成 */ get IsFinishSelect() { return this.SelectOptions.length == this.Answer.length && this.SelectOptions.length > 0 } /** * 是否单选 */ get IsRadio() { return this.Answer.length == 1 } /** * 是否正确 */ get IsRight() { return this.IsFinishSelect && this.Answer.every((item) => { return this.SelectOptions.indexOf(item) >= 0 }) } }