...
This commit is contained in:
@@ -1,15 +1,17 @@
|
||||
import 'dart:async'; // 👈 [추가] Timer
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:service_api/service_api.dart';
|
||||
import 'package:service_api/service_api.dart';
|
||||
import 'package:function_tree/function_tree.dart';
|
||||
import 'math_quiz_generator.dart';
|
||||
import '../models/math_quiz_models.dart';
|
||||
import '../models/math_quiz_difficulty.dart'; // 👈 MathQuizDifficulty 정의 필요
|
||||
|
||||
class MathQuizController with ChangeNotifier {
|
||||
late final MathQuizDifficulty difficulty;
|
||||
late final MathQuizPuzzle puzzle;
|
||||
late final String userId;
|
||||
late final String? userName;
|
||||
|
||||
late MathQuizPuzzle puzzle;
|
||||
late List<String?> _userAnswers;
|
||||
List<String?> get userAnswers => _userAnswers;
|
||||
|
||||
@@ -19,78 +21,142 @@ class MathQuizController with ChangeNotifier {
|
||||
bool _isGameCompleted = false;
|
||||
bool get isGameCompleted => _isGameCompleted;
|
||||
|
||||
// 🔽 [추가] 타이머 및 시간
|
||||
Timer? _timer;
|
||||
int _secondsElapsed = 0;
|
||||
int get secondsElapsed => _secondsElapsed;
|
||||
|
||||
// 🔽 [추가] 컨트롤러가 제거될 때 타이머 해제
|
||||
|
||||
late final int _totalPuzzlesInLevel;
|
||||
int _currentPuzzleIndex = 0;
|
||||
int get totalPuzzlesInLevel => _totalPuzzlesInLevel;
|
||||
int get currentPuzzleIndex => _currentPuzzleIndex;
|
||||
|
||||
bool _isWrongAnswer = false;
|
||||
bool get isWrongAnswer => _isWrongAnswer;
|
||||
|
||||
int _totalBlanksFilled = 0;
|
||||
int get totalBlanksFilled => _totalBlanksFilled;
|
||||
|
||||
int _remainingTries = 3;
|
||||
int get remainingTries => _remainingTries;
|
||||
|
||||
bool _isRevealingAnswer = false;
|
||||
bool get isRevealingAnswer => _isRevealingAnswer;
|
||||
|
||||
/// 현재 선택된 빈칸의 타입을 반환
|
||||
PuzzleBlankType? get currentSelectedBlankType {
|
||||
if (puzzle.blankTypes.isEmpty ||
|
||||
_selectedBlankIndex < 0 ||
|
||||
_selectedBlankIndex >= puzzle.blankTypes.length) {
|
||||
return null;
|
||||
}
|
||||
return puzzle.blankTypes[_selectedBlankIndex];
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// 🔽 [추가] 타이머 시작
|
||||
void _startTimer() {
|
||||
_timer?.cancel();
|
||||
_secondsElapsed = 0;
|
||||
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
_secondsElapsed++;
|
||||
notifyListeners(); // 매초 UI 갱신 (시간 표시용)
|
||||
notifyListeners();
|
||||
});
|
||||
}
|
||||
|
||||
// 🔽 [추가] 타이머 정지
|
||||
void _stopTimer() {
|
||||
_timer?.cancel();
|
||||
}
|
||||
|
||||
/// 1. 로비에서 호출: 새 게임 시작
|
||||
void startNewGame(MathQuizDifficulty level, String userId, String? userName) {
|
||||
this.difficulty = level;
|
||||
this.userId = userId;
|
||||
this.userName = userName;
|
||||
_totalPuzzlesInLevel = level.puzzleCount;
|
||||
_currentPuzzleIndex = 0;
|
||||
_isGameCompleted = false;
|
||||
_totalBlanksFilled = 0;
|
||||
_loadNextPuzzle();
|
||||
_startTimer();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// [🔥 수정] 문제 로드 시 로그 추가
|
||||
void _loadNextPuzzle() {
|
||||
final generator = MathQuizGenerator();
|
||||
this.puzzle = generator.generatePuzzle(level);
|
||||
this.puzzle = generator.generatePuzzle(difficulty);
|
||||
|
||||
// --- [LOG: 문제 구조 확인] ---
|
||||
debugPrint("--- MATH QUIZ PUZZLE LOADED (${difficulty.contextId}) ---");
|
||||
debugPrint("Grid: ${puzzle.gridCells}");
|
||||
debugPrint("Solutions (S): ${puzzle.solutions}");
|
||||
debugPrint("Blank Types (T): ${puzzle.blankTypes}");
|
||||
debugPrint("Total Blanks: ${puzzle.solutions.length}");
|
||||
debugPrint("------------------------------------------");
|
||||
// ----------------------------
|
||||
|
||||
_userAnswers = List.generate(puzzle.solutions.length, (_) => null);
|
||||
_selectedBlankIndex = 0;
|
||||
_isGameCompleted = false;
|
||||
|
||||
_startTimer(); // 👈 [추가]
|
||||
|
||||
notifyListeners();
|
||||
_isWrongAnswer = false;
|
||||
_remainingTries = 3;
|
||||
_isRevealingAnswer = false;
|
||||
}
|
||||
|
||||
/// 2. UI(빈칸)에서 호출: 빈칸 선택
|
||||
/// [🔥 수정] 빈칸 선택 시 로그 추가
|
||||
void onBlankTapped(int index) {
|
||||
if (_isGameCompleted) return;
|
||||
|
||||
_selectedBlankIndex = index;
|
||||
notifyListeners();
|
||||
if (_isGameCompleted || _isRevealingAnswer) return;
|
||||
if (_selectedBlankIndex != index) {
|
||||
_selectedBlankIndex = index;
|
||||
|
||||
// --- [LOG: 선택된 빈칸 타입 확인] ---
|
||||
final selectedType = currentSelectedBlankType?.toString() ?? 'None/Invalid';
|
||||
debugPrint("[LOG] BLANK TAPPED: Index $index selected.");
|
||||
debugPrint("[LOG] BLANK TAPPED: Determined Type: $selectedType");
|
||||
// ----------------------------------
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// 3. UI(숫자 버튼)에서 호출: 답 입력
|
||||
void onOptionTapped(String option) {
|
||||
if (_isGameCompleted) return;
|
||||
if (_isGameCompleted || _isRevealingAnswer) return;
|
||||
_isWrongAnswer = false;
|
||||
|
||||
if (_selectedBlankIndex >= puzzle.blankTypes.length) return;
|
||||
final PuzzleBlankType requiredType = puzzle.blankTypes[_selectedBlankIndex];
|
||||
final bool isOptionNumber = int.tryParse(option) != null;
|
||||
final bool isOptionOperator = ['+', '-', '*', '/'].contains(option);
|
||||
|
||||
if (requiredType == PuzzleBlankType.number && !isOptionNumber) {
|
||||
return;
|
||||
}
|
||||
if (requiredType == PuzzleBlankType.operator && !isOptionOperator) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_selectedBlankIndex < _userAnswers.length) {
|
||||
_userAnswers[_selectedBlankIndex] = option;
|
||||
}
|
||||
|
||||
_userAnswers[_selectedBlankIndex] = option;
|
||||
_selectNextBlank();
|
||||
notifyListeners();
|
||||
_checkCompletion();
|
||||
}
|
||||
|
||||
/// 4. UI(지우기 버튼)에서 호출: 답 지우기
|
||||
|
||||
void onClearTapped() {
|
||||
if (_isGameCompleted) return;
|
||||
_userAnswers[_selectedBlankIndex] = null;
|
||||
if (_isGameCompleted || _isRevealingAnswer) return;
|
||||
_isWrongAnswer = false;
|
||||
if (_selectedBlankIndex < _userAnswers.length) {
|
||||
_userAnswers[_selectedBlankIndex] = null;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 다음 빈칸 (아직 답이 없는)으로 자동 이동
|
||||
void _selectNextBlank() {
|
||||
if (_userAnswers.isEmpty) return;
|
||||
int nextIndex = (_selectedBlankIndex + 1) % _userAnswers.length;
|
||||
for (int i = 0; i < _userAnswers.length; i++) {
|
||||
if (_userAnswers[nextIndex] == null) {
|
||||
@@ -101,27 +167,104 @@ class MathQuizController with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// 모든 답이 채워졌는지, 그리고 정답인지 확인
|
||||
void _checkCompletion() {
|
||||
if (_userAnswers.any((answer) => answer == null)) {
|
||||
return;
|
||||
_isWrongAnswer = false;
|
||||
return;
|
||||
}
|
||||
|
||||
bool allCorrect = true;
|
||||
bool fastMatch = true;
|
||||
for (int i = 0; i < puzzle.solutions.length; i++) {
|
||||
if (_userAnswers[i] != puzzle.solutions[i]) {
|
||||
allCorrect = false;
|
||||
fastMatch = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (allCorrect) {
|
||||
_isGameCompleted = true;
|
||||
_stopTimer(); // 👈 [추가]
|
||||
notifyListeners();
|
||||
if (fastMatch) {
|
||||
_handleCorrectAnswer();
|
||||
return;
|
||||
}
|
||||
bool slowMatch = _checkSlowPathValidation();
|
||||
if (slowMatch) {
|
||||
_handleCorrectAnswer();
|
||||
} else {
|
||||
// [TODO] 오답 처리 (예: 스낵바 표시)
|
||||
debugPrint("오답입니다!");
|
||||
_handleWrongAnswer();
|
||||
}
|
||||
}
|
||||
|
||||
bool _checkSlowPathValidation() {
|
||||
List<String> rebuiltGrid = List.of(puzzle.gridCells);
|
||||
int answerIndex = 0;
|
||||
for (int i = 0; i < rebuiltGrid.length; i++) {
|
||||
if (rebuiltGrid[i] == '?') {
|
||||
if (answerIndex < _userAnswers.length) {
|
||||
rebuiltGrid[i] = _userAnswers[answerIndex]!;
|
||||
answerIndex++;
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
for (final eq in puzzle.equations) {
|
||||
final String expression =
|
||||
eq.expressionIndices.map((i) => rebuiltGrid[i]).join(' ');
|
||||
final String expectedResultStr = rebuiltGrid[eq.resultIndex];
|
||||
if (expression.contains('=') ||
|
||||
expectedResultStr.contains(RegExp(r'[+\-*/]'))) {
|
||||
return false;
|
||||
}
|
||||
final num actualResult = expression.interpret();
|
||||
final num expectedResult = num.parse(expectedResultStr);
|
||||
if (actualResult != expectedResult) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
debugPrint("방정식 평가 실패: $e");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void _handleCorrectAnswer() {
|
||||
_isWrongAnswer = false;
|
||||
_totalBlanksFilled += _userAnswers.length;
|
||||
if (_currentPuzzleIndex + 1 < _totalPuzzlesInLevel) {
|
||||
_currentPuzzleIndex++;
|
||||
_loadNextPuzzle();
|
||||
notifyListeners();
|
||||
} else {
|
||||
_isGameCompleted = true;
|
||||
_stopTimer();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
void _handleWrongAnswer() {
|
||||
_remainingTries--;
|
||||
_isWrongAnswer = true;
|
||||
if (_remainingTries <= 0) {
|
||||
_handleFailedAnswer();
|
||||
} else {
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
void _handleFailedAnswer() {
|
||||
_isWrongAnswer = false;
|
||||
_isRevealingAnswer = true;
|
||||
_userAnswers = List.of(puzzle.solutions);
|
||||
notifyListeners();
|
||||
Future.delayed(const Duration(seconds: 3), () {
|
||||
if (!_isGameCompleted) {
|
||||
if (_currentPuzzleIndex + 1 < _totalPuzzlesInLevel) {
|
||||
_currentPuzzleIndex++;
|
||||
_loadNextPuzzle();
|
||||
notifyListeners();
|
||||
} else {
|
||||
_isGameCompleted = true;
|
||||
_stopTimer();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,42 +1,54 @@
|
||||
// packages/feature_game_mathquiz/lib/controllers/math_quiz_generator.dart
|
||||
import 'dart:math';
|
||||
import 'package:flutter/material.dart'; // debugPrint 사용을 위해 유지
|
||||
import 'package:service_api/service_api.dart';
|
||||
import '../models/math_quiz_difficulty.dart';
|
||||
import '../models/math_quiz_models.dart';
|
||||
import 'package:function_tree/function_tree.dart';
|
||||
|
||||
class MathQuizGenerator {
|
||||
final Random _random = Random();
|
||||
|
||||
/// 문자열이 연산자인지 확인
|
||||
bool _isOperator(String value) {
|
||||
return ['+', '-', '*', '/'].contains(value);
|
||||
}
|
||||
|
||||
/// 난이도에 맞는 퍼즐을 생성합니다.
|
||||
MathQuizPuzzle generatePuzzle(MathQuizDifficulty level) {
|
||||
switch (level.layout) {
|
||||
case MathQuizLayout.singleLine:
|
||||
if (level.operationCount == 2) { // Lv 1-5
|
||||
return _generateSimpleEquation(level); // A + B = C
|
||||
} else { // operationCount == 3 (Lv 6-10)
|
||||
return _generateMultiOpEquation(level); // A + B * C = D
|
||||
if (level.operationCount == 2) {
|
||||
return _generateSimpleEquation(level);
|
||||
} else {
|
||||
return _generateMultiOpEquation(level);
|
||||
}
|
||||
case MathQuizLayout.linkedL: // operationCount == 4 (Lv 11-15)
|
||||
return _generateLinkedEquations(level); // 2x2 그리드
|
||||
case MathQuizLayout.gridSquare:
|
||||
if (level.operationCount == 9) { // Lv 10-12 (3x3)
|
||||
return _generate3x3GridEquation(level);
|
||||
} else { // Lv 13-15 (4x4)
|
||||
case MathQuizLayout.dualLine:
|
||||
return _generateDualLineEquation(level);
|
||||
case MathQuizLayout.linkedL:
|
||||
return _generateLinkedEquations(level);
|
||||
case MathQuizLayout.gridSquare:
|
||||
if (level.operationCount == 9) {
|
||||
return _generate3x3GridEquation(level);
|
||||
} else {
|
||||
return _generate4x4GridEquation(level);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [Lv 1-5] 숫자 2개 연산: (A op B = C)
|
||||
/// [Lv 1-3] 숫자 2개 연산: (A op B = C)
|
||||
MathQuizPuzzle _generateSimpleEquation(MathQuizDifficulty level) {
|
||||
// (이전과 동일)
|
||||
final (int a, int b, int c, String op) = _createEquation(level.operators);
|
||||
final List<String> allParts = (op == '+')
|
||||
? [a.toString(), op, b.toString(), '=', c.toString()]
|
||||
: (op == '-')
|
||||
? [c.toString(), op, a.toString(), '=', b.toString()]
|
||||
: (op == '*')
|
||||
? [a.toString(), op, b.toString(), '=', c.toString()]
|
||||
: [c.toString(), op, a.toString(), '=', b.toString()];
|
||||
? [c.toString(), op, a.toString(), '=', b.toString()]
|
||||
: (op == '*')
|
||||
? [a.toString(), op, b.toString(), '=', c.toString()]
|
||||
: [c.toString(), op, a.toString(), '=', b.toString()];
|
||||
|
||||
debugPrint("--- GEN LOG (Lv 1-3): ALL PARTS: $allParts"); // [LOG]
|
||||
|
||||
List<int> candidateIndices;
|
||||
switch (level.blankType) {
|
||||
case MathQuizBlankType.numbersOnly: candidateIndices = [0, 2]; break;
|
||||
@@ -45,35 +57,62 @@ class MathQuizGenerator {
|
||||
}
|
||||
final int finalBlankCount = min(level.blankCount, candidateIndices.length);
|
||||
final List<int> blankIndices = (candidateIndices..shuffle(_random)).sublist(0, finalBlankCount);
|
||||
|
||||
blankIndices.sort(); // 👈 FIX
|
||||
|
||||
final List<String> solutions = [];
|
||||
final List<PuzzleBlankType> finalBlankTypes = [];
|
||||
final List<String> gridCells = List.of(allParts);
|
||||
for (int index in blankIndices) {
|
||||
solutions.add(allParts[index]);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
final Set<String> optionsSet = solutions.toSet();
|
||||
while (optionsSet.length < 9) {
|
||||
optionsSet.add((_random.nextInt(9) + 1).toString());
|
||||
final String solutionValue = allParts[index];
|
||||
solutions.add(solutionValue);
|
||||
finalBlankTypes.add(_isOperator(solutionValue)
|
||||
? PuzzleBlankType.operator
|
||||
: PuzzleBlankType.number);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
|
||||
debugPrint("--- GEN LOG (Lv 1-3): BLANK INDICES: $blankIndices"); // [LOG]
|
||||
debugPrint("--- GEN LOG (Lv 1-3): SOLUTIONS: $solutions | TYPES: $finalBlankTypes"); // [LOG]
|
||||
|
||||
final Set<String> optionsSet = solutions.toSet();
|
||||
while (optionsSet.length < 9) { optionsSet.add((_random.nextInt(9) + 1).toString()); }
|
||||
optionsSet.addAll(level.operators.split(','));
|
||||
if (level.blankType != MathQuizBlankType.operatorsOnly) {
|
||||
optionsSet.add('=');
|
||||
}
|
||||
if (level.blankType != MathQuizBlankType.operatorsOnly) { optionsSet.add('='); }
|
||||
final List<String> options = (optionsSet.toList()..shuffle(_random)).toList();
|
||||
|
||||
return MathQuizPuzzle(
|
||||
gridCells: gridCells,
|
||||
gridCrossAxisCount: 5, // 5x1 그리드
|
||||
solutions: solutions,
|
||||
gridCrossAxisCount: 5,
|
||||
options: options,
|
||||
solutions: solutions,
|
||||
blankTypes: finalBlankTypes,
|
||||
equations: [
|
||||
MathQuizEquation(expressionIndices: [0, 1, 2], resultIndex: 4),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// [Lv 6-10] 숫자 3개 연산: (A op1 B op2 C = D)
|
||||
/// [Lv 4-6] 숫자 3개 연산: (A op1 B op2 C = D)
|
||||
MathQuizPuzzle _generateMultiOpEquation(MathQuizDifficulty level) {
|
||||
// 1. 식 생성 (연산자 우선순위 포함)
|
||||
final (int a, int b, int c, String op1, String op2, int result) = _createMultiOpEquation(level.operators);
|
||||
final List<String> allParts = [a.toString(), op1, b.toString(), op2, c.toString(), '=', result.toString()];
|
||||
// 2. 빈칸 생성
|
||||
|
||||
// [LOG 1] 튜플 생성 직후 값 확인
|
||||
debugPrint("--- GEN LOG: TUPLE: a=$a, op1=$op1, b=$b, op2=$op2, c=$c, R=$result");
|
||||
|
||||
final List<String> allParts = [
|
||||
a.toString(),
|
||||
op1,
|
||||
b.toString(),
|
||||
op2,
|
||||
c.toString(),
|
||||
'=',
|
||||
result.toString()
|
||||
];
|
||||
|
||||
// [LOG 2] allParts 리스트 완성 직후 값 확인
|
||||
debugPrint("--- GEN LOG (Lv 4-6): ALL PARTS: $allParts");
|
||||
|
||||
final int blankCount = level.blankCount;
|
||||
List<int> candidateIndices;
|
||||
switch (level.blankType) {
|
||||
@@ -83,31 +122,110 @@ class MathQuizGenerator {
|
||||
}
|
||||
final int finalBlankCount = min(blankCount, candidateIndices.length);
|
||||
final List<int> blankIndices = (candidateIndices..shuffle(_random)).sublist(0, finalBlankCount);
|
||||
|
||||
blankIndices.sort(); // 👈 FIX
|
||||
|
||||
// [LOG 3] blankIndices 리스트 결정 직후 확인
|
||||
debugPrint("--- GEN LOG (Lv 4-6): BLANK INDICES: $blankIndices");
|
||||
|
||||
final List<String> solutions = [];
|
||||
final List<PuzzleBlankType> finalBlankTypes = [];
|
||||
final List<String> gridCells = List.of(allParts);
|
||||
for (int index in blankIndices) {
|
||||
solutions.add(allParts[index]);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
// 3. 옵션 생성
|
||||
final Set<String> optionsSet = solutions.toSet();
|
||||
while (optionsSet.length < 9) {
|
||||
optionsSet.add((_random.nextInt(9) + 1).toString());
|
||||
final String solutionValue = allParts[index];
|
||||
solutions.add(solutionValue);
|
||||
finalBlankTypes.add(_isOperator(solutionValue)
|
||||
? PuzzleBlankType.operator
|
||||
: PuzzleBlankType.number);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
|
||||
debugPrint("--- GEN LOG (Lv 4-6): SOLUTIONS: $solutions | TYPES: $finalBlankTypes"); // [LOG]
|
||||
|
||||
|
||||
final Set<String> optionsSet = solutions.toSet();
|
||||
while (optionsSet.length < 9) { optionsSet.add((_random.nextInt(9) + 1).toString()); }
|
||||
optionsSet.addAll(level.operators.split(','));
|
||||
optionsSet.add('=');
|
||||
// 4. 그리드 모델로 반환
|
||||
|
||||
return MathQuizPuzzle(
|
||||
gridCells: gridCells,
|
||||
gridCrossAxisCount: 7, // 7x1 그리드
|
||||
solutions: solutions,
|
||||
gridCrossAxisCount: 7,
|
||||
options: (optionsSet.toList()..shuffle(_random)).toList(),
|
||||
solutions: solutions,
|
||||
blankTypes: finalBlankTypes,
|
||||
equations: [
|
||||
MathQuizEquation(expressionIndices: [0, 1, 2, 3, 4], resultIndex: 6),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// [Lv 11-15] 숫자 4개 연산: (2x2 그리드 'ㄱ', 'ㄴ')
|
||||
/// [Lv 7-9] 독립된 2줄 (A op B = C, D op E = F)
|
||||
MathQuizPuzzle _generateDualLineEquation(MathQuizDifficulty level) {
|
||||
final (int a, int b, int c, String op1) = _createEquation(level.operators);
|
||||
final (int d, int e, int f, String op2) = _createEquation(level.operators);
|
||||
|
||||
final List<String> allParts = [
|
||||
a.toString(), op1, b.toString(), "=", c.toString(),
|
||||
" ", " ", " ", " ", " ",
|
||||
d.toString(), op2, e.toString(), "=", f.toString(),
|
||||
];
|
||||
debugPrint("--- GEN LOG (Lv 7-9 DUAL): ALL PARTS: $allParts"); // [LOG]
|
||||
|
||||
|
||||
List<int> numberIndices = [0, 2, 10, 12];
|
||||
List<int> operatorIndices = [1, 11];
|
||||
List<int> blankIndices = [];
|
||||
switch (level.blankType) {
|
||||
case MathQuizBlankType.numbersOnly:
|
||||
blankIndices = (numberIndices..shuffle(_random)).sublist(0, min(level.blankCount, numberIndices.length));
|
||||
break;
|
||||
case MathQuizBlankType.operatorsOnly:
|
||||
blankIndices = (operatorIndices..shuffle(_random)).sublist(0, min(level.blankCount, operatorIndices.length));
|
||||
break;
|
||||
case MathQuizBlankType.numbersAndOperators:
|
||||
blankIndices = (numberIndices + operatorIndices..shuffle(_random)).sublist(0, level.blankCount);
|
||||
break;
|
||||
}
|
||||
|
||||
blankIndices.sort(); // 👈 FIX
|
||||
|
||||
final List<String> solutions = [];
|
||||
final List<PuzzleBlankType> finalBlankTypes = [];
|
||||
final List<String> gridCells = List.of(allParts);
|
||||
for (int index in blankIndices) {
|
||||
final String solutionValue = allParts[index];
|
||||
solutions.add(solutionValue);
|
||||
finalBlankTypes.add(_isOperator(solutionValue)
|
||||
? PuzzleBlankType.operator
|
||||
: PuzzleBlankType.number);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
|
||||
debugPrint("--- GEN LOG (Lv 7-9 DUAL): BLANK INDICES: $blankIndices"); // [LOG]
|
||||
debugPrint("--- GEN LOG (Lv 7-9 DUAL): SOLUTIONS: $solutions | TYPES: $finalBlankTypes"); // [LOG]
|
||||
|
||||
|
||||
final Set<String> optionsSet = solutions.toSet();
|
||||
while (optionsSet.length < 9) { optionsSet.add((_random.nextInt(9) + 1).toString()); }
|
||||
optionsSet.addAll(level.operators.split(','));
|
||||
optionsSet.add('=');
|
||||
|
||||
return MathQuizPuzzle(
|
||||
gridCells: gridCells,
|
||||
gridCrossAxisCount: 5,
|
||||
options: (optionsSet.toList()..shuffle(_random)).toList(),
|
||||
solutions: solutions,
|
||||
blankTypes: finalBlankTypes,
|
||||
equations: [
|
||||
MathQuizEquation(expressionIndices: [0, 1, 2], resultIndex: 4),
|
||||
MathQuizEquation(expressionIndices: [10, 11, 12], resultIndex: 14),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// [Lv 10-12] 숫자 4개 연산: (2x2 그리드 'ㄱ', 'ㄴ')
|
||||
MathQuizPuzzle _generateLinkedEquations(MathQuizDifficulty level) {
|
||||
// (동적 생성 로직)
|
||||
while (true) {
|
||||
final int a = _random.nextInt(9) + 1;
|
||||
final int b = _random.nextInt(9) + 1;
|
||||
@@ -118,24 +236,23 @@ class MathQuizGenerator {
|
||||
final String op2 = (ops..shuffle(_random)).first;
|
||||
final String op3 = (ops..shuffle(_random)).first;
|
||||
final String op4 = (ops..shuffle(_random)).first;
|
||||
final int? r1 = _calculate(a, b, op1);
|
||||
final int? r2 = _calculate(c, d, op2);
|
||||
final int? r3 = _calculate(a, c, op3);
|
||||
final int? r4 = _calculate(b, d, op4);
|
||||
final int? r1 = _calculate(a, b, op1);
|
||||
final int? r2 = _calculate(c, d, op2);
|
||||
final int? r3 = _calculate(a, c, op3);
|
||||
final int? r4 = _calculate(b, d, op4);
|
||||
if (r1 == null || r2 == null || r3 == null || r4 == null) continue;
|
||||
if (r1 < -99 || r2 < -99 || r3 < -99 || r4 < -99 || r1 > 999 || r2 > 999 || r3 > 999 || r4 > 999) continue;
|
||||
|
||||
final List<String> allParts = [
|
||||
a.toString(), op1, b.toString(), "=", r1.toString(),
|
||||
op3, " ", op4, " ", "=",
|
||||
op3, " ", op4, " ", "=",
|
||||
c.toString(), op2, d.toString(), "=", r2.toString(),
|
||||
"=", " ", "=", " ", "=",
|
||||
"=", " ", "=", " ", "=",
|
||||
r3.toString(), " ", r4.toString(), " ", " ",
|
||||
];
|
||||
final List<String> solutions = [];
|
||||
final List<String> gridCells = List.of(allParts);
|
||||
List<int> numberIndices = [0, 2, 10, 12]; // A,B,C,D
|
||||
List<int> operatorIndices = [1, 5, 7, 11]; // op1,op3,op4,op2
|
||||
debugPrint("--- GEN LOG (Lv 10-12 LINKED): ALL PARTS: $allParts"); // [LOG]
|
||||
|
||||
List<int> numberIndices = [0, 2, 10, 12];
|
||||
List<int> operatorIndices = [1, 5, 7, 11];
|
||||
List<int> blankIndices = [];
|
||||
switch (level.blankType) {
|
||||
case MathQuizBlankType.numbersOnly:
|
||||
@@ -148,165 +265,244 @@ class MathQuizGenerator {
|
||||
blankIndices = (numberIndices + operatorIndices..shuffle(_random)).sublist(0, level.blankCount);
|
||||
break;
|
||||
}
|
||||
blankIndices.sort();
|
||||
|
||||
blankIndices.sort(); // 👈 FIX
|
||||
|
||||
final List<String> solutions = [];
|
||||
final List<PuzzleBlankType> finalBlankTypes = [];
|
||||
final List<String> gridCells = List.of(allParts);
|
||||
for (int index in blankIndices) {
|
||||
solutions.add(allParts[index]);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
final Set<String> optionsSet = solutions.toSet();
|
||||
while (optionsSet.length < 9) {
|
||||
optionsSet.add((_random.nextInt(9) + 1).toString());
|
||||
final String solutionValue = allParts[index];
|
||||
solutions.add(solutionValue);
|
||||
finalBlankTypes.add(_isOperator(solutionValue)
|
||||
? PuzzleBlankType.operator
|
||||
: PuzzleBlankType.number);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
|
||||
debugPrint("--- GEN LOG (Lv 10-12 LINKED): BLANK INDICES: $blankIndices"); // [LOG]
|
||||
debugPrint("--- GEN LOG (Lv 10-12 LINKED): SOLUTIONS: $solutions | TYPES: $finalBlankTypes"); // [LOG]
|
||||
|
||||
final Set<String> optionsSet = solutions.toSet();
|
||||
while (optionsSet.length < 9) { optionsSet.add((_random.nextInt(9) + 1).toString()); }
|
||||
optionsSet.addAll(level.operators.split(','));
|
||||
optionsSet.add('=');
|
||||
|
||||
|
||||
return MathQuizPuzzle(
|
||||
gridCells: gridCells,
|
||||
gridCrossAxisCount: 5, // 5x5 그리드
|
||||
solutions: solutions,
|
||||
gridCrossAxisCount: 5,
|
||||
options: (optionsSet.toList()..shuffle(_random)).toList(),
|
||||
solutions: solutions,
|
||||
blankTypes: finalBlankTypes,
|
||||
equations: [
|
||||
MathQuizEquation(expressionIndices: [0, 1, 2], resultIndex: 4),
|
||||
MathQuizEquation(expressionIndices: [10, 11, 12], resultIndex: 14),
|
||||
MathQuizEquation(expressionIndices: [0, 5, 10], resultIndex: 20),
|
||||
MathQuizEquation(expressionIndices: [2, 7, 12], resultIndex: 22),
|
||||
],
|
||||
);
|
||||
} // end while(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// [수정됨] 레벨 10-12 (3x3 Grid) - 템플릿 목록 사용
|
||||
/// [Lv 13-15] 3x3 Grid - 동적 생성
|
||||
MathQuizPuzzle _generate3x3GridEquation(MathQuizDifficulty level) {
|
||||
// 1. 3x3 템플릿 목록에서 랜덤 선택
|
||||
final template = _get3x3Templates()..shuffle();
|
||||
final selectedTemplate = template.first;
|
||||
|
||||
final List<String> allParts = selectedTemplate.gridCells;
|
||||
final List<int> numberIndices = selectedTemplate.numberIndices;
|
||||
final List<int> operatorIndices = selectedTemplate.operatorIndices;
|
||||
while (true) {
|
||||
try {
|
||||
final ops = level.operators.split(',');
|
||||
final n = List.generate(9, (_) => _random.nextInt(9) + 1);
|
||||
final o = List.generate(12, (_) => (ops..shuffle(_random)).first);
|
||||
final expr = [
|
||||
"${n[0]} ${o[0]} ${n[1]} ${o[1]} ${n[2]}", // R0
|
||||
"${n[3]} ${o[5]} ${n[4]} ${o[6]} ${n[5]}", // R1
|
||||
"${n[6]} ${o[10]} ${n[7]} ${o[11]} ${n[8]}", // R2
|
||||
"${n[0]} ${o[2]} ${n[3]} ${o[7]} ${n[6]}", // R3
|
||||
"${n[1]} ${o[3]} ${n[4]} ${o[8]} ${n[7]}", // R4
|
||||
"${n[2]} ${o[4]} ${n[5]} ${o[9]} ${n[8]}", // R5
|
||||
];
|
||||
final List<num> r = expr.map((e) => e.interpret()).toList();
|
||||
if (r.any((res) => res.toInt() != res || res < -99 || res > 999)) { continue; }
|
||||
final List<int> rInt = r.map((res) => res.toInt()).toList();
|
||||
final List<String> allParts = [
|
||||
n[0].toString(), o[0], n[1].toString(), o[1], n[2].toString(), "=", rInt[0].toString(),
|
||||
o[2], " ", o[3], " ", o[4], " ", "=",
|
||||
n[3].toString(), o[5], n[4].toString(), o[6], n[5].toString(), "=", rInt[1].toString(),
|
||||
o[7], " ", o[8], " ", o[9], " ", "=",
|
||||
n[6].toString(), o[10], n[7].toString(), o[11], n[8].toString(), "=", rInt[2].toString(),
|
||||
"=", " ", "=", " ", "=", " ", "=",
|
||||
rInt[3].toString(), " ", rInt[4].toString(), " ", rInt[5].toString(), " ", " ",
|
||||
];
|
||||
debugPrint("--- GEN LOG (Lv 13-15 Grid): ALL PARTS: $allParts"); // [LOG]
|
||||
|
||||
// 2. 난이도(level.blankType)에 따라 빈칸('?') 생성
|
||||
final List<String> finalSolutions = [];
|
||||
final List<String> gridCells = List.of(allParts);
|
||||
|
||||
List<int> blankIndices = [];
|
||||
switch (level.blankType) {
|
||||
case MathQuizBlankType.numbersOnly:
|
||||
blankIndices = (numberIndices..shuffle(_random)).sublist(0, min(level.blankCount, numberIndices.length));
|
||||
break;
|
||||
case MathQuizBlankType.operatorsOnly:
|
||||
blankIndices = (operatorIndices..shuffle(_random)).sublist(0, min(level.blankCount, operatorIndices.length));
|
||||
break;
|
||||
case MathQuizBlankType.numbersAndOperators:
|
||||
blankIndices = (numberIndices + operatorIndices..shuffle(_random)).sublist(0, level.blankCount);
|
||||
break;
|
||||
}
|
||||
|
||||
// 3. 빈칸 적용
|
||||
blankIndices.sort();
|
||||
for (int index in blankIndices) {
|
||||
finalSolutions.add(allParts[index]);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
|
||||
// 4. 옵션 생성
|
||||
final Set<String> optionsSet = finalSolutions.toSet(); // 👈 [오류 수정]
|
||||
while (optionsSet.length < 9) {
|
||||
optionsSet.add((_random.nextInt(9) + 1).toString());
|
||||
}
|
||||
optionsSet.addAll(level.operators.split(','));
|
||||
optionsSet.add('=');
|
||||
|
||||
final List<String> options = (optionsSet.toList()..shuffle(_random)).toList();
|
||||
|
||||
return MathQuizPuzzle(
|
||||
gridCells: gridCells,
|
||||
gridCrossAxisCount: 7, // 3x3 퍼즐 (7x7 그리드)
|
||||
solutions: finalSolutions,
|
||||
options: options, // 👈 [오류 수정]
|
||||
);
|
||||
final List<int> numberIndices = [0, 2, 4, 14, 16, 18, 28, 30, 32];
|
||||
final List<int> operatorIndices = [1, 3, 7, 9, 11, 15, 17, 21, 23, 25, 29, 31];
|
||||
List<int> blankIndices = [];
|
||||
switch (level.blankType) {
|
||||
case MathQuizBlankType.numbersOnly:
|
||||
blankIndices = (numberIndices..shuffle(_random)).sublist(0, min(level.blankCount, numberIndices.length));
|
||||
break;
|
||||
case MathQuizBlankType.operatorsOnly:
|
||||
blankIndices = (operatorIndices..shuffle(_random)).sublist(0, min(level.blankCount, operatorIndices.length));
|
||||
break;
|
||||
case MathQuizBlankType.numbersAndOperators:
|
||||
blankIndices = (numberIndices + operatorIndices..shuffle(_random)).sublist(0, level.blankCount);
|
||||
break;
|
||||
}
|
||||
|
||||
blankIndices.sort(); // 👈 FIX
|
||||
|
||||
final List<String> solutions = [];
|
||||
final List<PuzzleBlankType> finalBlankTypes = [];
|
||||
final List<String> gridCells = List.of(allParts);
|
||||
for (int index in blankIndices) {
|
||||
final String solutionValue = allParts[index];
|
||||
solutions.add(solutionValue);
|
||||
finalBlankTypes.add(_isOperator(solutionValue)
|
||||
? PuzzleBlankType.operator
|
||||
: PuzzleBlankType.number);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
|
||||
debugPrint("--- GEN LOG (Lv 13-15 Grid): BLANK INDICES: $blankIndices"); // [LOG]
|
||||
debugPrint("--- GEN LOG (Lv 13-15 Grid): SOLUTIONS: $solutions | TYPES: $finalBlankTypes"); // [LOG]
|
||||
|
||||
|
||||
final Set<String> optionsSet = solutions.toSet();
|
||||
while (optionsSet.length < 9) { optionsSet.add((_random.nextInt(9) + 1).toString()); }
|
||||
optionsSet.addAll(level.operators.split(','));
|
||||
optionsSet.add('=');
|
||||
final List<String> options = (optionsSet.toList()..shuffle(_random)).toList();
|
||||
|
||||
return MathQuizPuzzle(
|
||||
gridCells: gridCells,
|
||||
gridCrossAxisCount: 7,
|
||||
options: options,
|
||||
solutions: solutions,
|
||||
blankTypes: finalBlankTypes,
|
||||
equations: [
|
||||
MathQuizEquation(expressionIndices: [0, 1, 2, 3, 4], resultIndex: 6),
|
||||
MathQuizEquation(expressionIndices: [14, 15, 16, 17, 18], resultIndex: 20),
|
||||
MathQuizEquation(expressionIndices: [28, 29, 30, 31, 32], resultIndex: 34),
|
||||
MathQuizEquation(expressionIndices: [0, 7, 14, 21, 28], resultIndex: 42),
|
||||
MathQuizEquation(expressionIndices: [2, 9, 16, 23, 30], resultIndex: 44),
|
||||
MathQuizEquation(expressionIndices: [4, 11, 18, 25, 32], resultIndex: 46),
|
||||
],
|
||||
);
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [수정됨] 레벨 13-15 (4x4 Grid) - 템플릿 목록 사용
|
||||
/// [Lv 16-19] 4x4 Grid - 동적 생성
|
||||
MathQuizPuzzle _generate4x4GridEquation(MathQuizDifficulty level) {
|
||||
// 1. 4x4 템플릿 목록에서 랜덤 선택
|
||||
final template = _get4x4Templates()..shuffle();
|
||||
final selectedTemplate = template.first;
|
||||
|
||||
final List<String> allParts = selectedTemplate.gridCells;
|
||||
final List<int> numberIndices = selectedTemplate.numberIndices;
|
||||
final List<int> operatorIndices = selectedTemplate.operatorIndices;
|
||||
while (true) {
|
||||
try {
|
||||
final ops = level.operators.split(',');
|
||||
final n = List.generate(16, (_) => _random.nextInt(9) + 1);
|
||||
final o = List.generate(24, (_) => (ops..shuffle(_random)).first);
|
||||
final expr = [
|
||||
"${n[0]} ${o[0]} ${n[1]} ${o[1]} ${n[2]} ${o[2]} ${n[3]}", // R0
|
||||
"${n[4]} ${o[3]} ${n[5]} ${o[4]} ${n[6]} ${o[5]} ${n[7]}", // R1
|
||||
"${n[8]} ${o[6]} ${n[9]} ${o[7]} ${n[10]} ${o[8]} ${n[11]}", // R2
|
||||
"${n[12]} ${o[9]} ${n[13]} ${o[10]} ${n[14]} ${o[11]} ${n[15]}", // R3
|
||||
"${n[0]} ${o[12]} ${n[4]} ${o[13]} ${n[8]} ${o[14]} ${n[12]}", // R4
|
||||
"${n[1]} ${o[15]} ${n[5]} ${o[16]} ${n[9]} ${o[17]} ${n[13]}", // R5
|
||||
"${n[2]} ${o[18]} ${n[6]} ${o[19]} ${n[10]} ${o[20]} ${n[14]}", // R6
|
||||
"${n[3]} ${o[21]} ${n[7]} ${o[22]} ${n[11]} ${o[23]} ${n[15]}", // R7
|
||||
];
|
||||
final List<num> r = expr.map((e) => e.interpret()).toList();
|
||||
if (r.any((res) => res.toInt() != res || res < -999 || res > 9999)) { continue; }
|
||||
final List<int> rInt = r.map((res) => res.toInt()).toList();
|
||||
final List<String> allParts = [
|
||||
n[0].toString(), o[0], n[1].toString(), o[1], n[2].toString(), o[2], n[3].toString(), "=", rInt[0].toString(),
|
||||
o[12], " ", o[15], " ", o[18], " ", o[21], " ", "=",
|
||||
n[4].toString(), o[3], n[5].toString(), o[4], n[6].toString(), o[5], n[7].toString(), "=", rInt[1].toString(),
|
||||
o[13], " ", o[16], " ", o[19], " ", o[22], " ", "=",
|
||||
n[8].toString(), o[6], n[9].toString(), o[7], n[10].toString(), o[8], n[11].toString(), "=", rInt[2].toString(),
|
||||
o[14], " ", o[17], " ", o[20], " ", o[23], " ", "=",
|
||||
n[12].toString(), o[9], n[13].toString(), o[10], n[14].toString(), o[11], n[15].toString(), "=", rInt[3].toString(),
|
||||
"=", " ", "=", " ", "=", " ", "=", " ", "=",
|
||||
rInt[4].toString(), " ", rInt[5].toString(), " ", rInt[6].toString(), " ", rInt[7].toString(), " ", " ",
|
||||
];
|
||||
debugPrint("--- GEN LOG (Lv 16-19 Grid): ALL PARTS: $allParts"); // [LOG]
|
||||
|
||||
// 2. 난이도(level.blankType)에 따라 빈칸('?') 생성
|
||||
final List<String> finalSolutions = [];
|
||||
final List<String> gridCells = List.of(allParts);
|
||||
|
||||
List<int> blankIndices = [];
|
||||
switch (level.blankType) {
|
||||
case MathQuizBlankType.numbersOnly:
|
||||
blankIndices = (numberIndices..shuffle(_random)).sublist(0, min(level.blankCount, numberIndices.length));
|
||||
break;
|
||||
case MathQuizBlankType.operatorsOnly:
|
||||
blankIndices = (operatorIndices..shuffle(_random)).sublist(0, min(level.blankCount, operatorIndices.length));
|
||||
break;
|
||||
case MathQuizBlankType.numbersAndOperators:
|
||||
blankIndices = (numberIndices + operatorIndices..shuffle(_random)).sublist(0, level.blankCount);
|
||||
break;
|
||||
}
|
||||
|
||||
// 3. 빈칸 적용
|
||||
blankIndices.sort();
|
||||
for (int index in blankIndices) {
|
||||
finalSolutions.add(allParts[index]);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
|
||||
// 4. 옵션 생성
|
||||
final Set<String> optionsSet = finalSolutions.toSet(); // 👈 [오류 수정]
|
||||
while (optionsSet.length < 9) {
|
||||
optionsSet.add((_random.nextInt(9) + 1).toString());
|
||||
}
|
||||
optionsSet.addAll(level.operators.split(','));
|
||||
optionsSet.add('=');
|
||||
|
||||
final List<String> options = (optionsSet.toList()..shuffle(_random)).toList();
|
||||
|
||||
return MathQuizPuzzle(
|
||||
gridCells: gridCells,
|
||||
gridCrossAxisCount: 9, // 4x4 퍼즐 (9x9 그리드)
|
||||
solutions: finalSolutions,
|
||||
options: options, // 👈 [오류 수정]
|
||||
);
|
||||
final List<int> numberIndices = [0, 2, 4, 6, 18, 20, 22, 24, 36, 38, 40, 42, 54, 56, 58, 60];
|
||||
final List<int> operatorIndices = [ 1, 3, 5, 9, 11, 13, 15, 19, 21, 23, 27, 29, 31, 33, 37, 39, 41, 45, 47, 49, 51, 55, 57, 59 ];
|
||||
List<int> blankIndices = [];
|
||||
switch (level.blankType) {
|
||||
case MathQuizBlankType.numbersOnly:
|
||||
blankIndices = (numberIndices..shuffle(_random)).sublist(0, min(level.blankCount, numberIndices.length));
|
||||
break;
|
||||
case MathQuizBlankType.operatorsOnly:
|
||||
blankIndices = (operatorIndices..shuffle(_random)).sublist(0, min(level.blankCount, operatorIndices.length));
|
||||
break;
|
||||
case MathQuizBlankType.numbersAndOperators:
|
||||
blankIndices = (numberIndices + operatorIndices..shuffle(_random)).sublist(0, level.blankCount);
|
||||
break;
|
||||
}
|
||||
|
||||
blankIndices.sort(); // 👈 FIX
|
||||
|
||||
final List<String> solutions = [];
|
||||
final List<PuzzleBlankType> finalBlankTypes = [];
|
||||
final List<String> gridCells = List.of(allParts);
|
||||
for (int index in blankIndices) {
|
||||
final String solutionValue = allParts[index];
|
||||
solutions.add(solutionValue);
|
||||
finalBlankTypes.add(_isOperator(solutionValue)
|
||||
? PuzzleBlankType.operator
|
||||
: PuzzleBlankType.number);
|
||||
gridCells[index] = '?';
|
||||
}
|
||||
|
||||
debugPrint("--- GEN LOG (Lv 16-19 Grid): BLANK INDICES: $blankIndices"); // [LOG]
|
||||
debugPrint("--- GEN LOG (Lv 16-19 Grid): SOLUTIONS: $solutions | TYPES: $finalBlankTypes"); // [LOG]
|
||||
|
||||
|
||||
final Set<String> optionsSet = solutions.toSet();
|
||||
while (optionsSet.length < 9) { optionsSet.add((_random.nextInt(9) + 1).toString()); }
|
||||
optionsSet.addAll(level.operators.split(','));
|
||||
optionsSet.add('=');
|
||||
final List<String> options = (optionsSet.toList()..shuffle(_random)).toList();
|
||||
|
||||
return MathQuizPuzzle(
|
||||
gridCells: gridCells,
|
||||
gridCrossAxisCount: 9,
|
||||
options: options,
|
||||
solutions: solutions,
|
||||
blankTypes: finalBlankTypes,
|
||||
equations: [
|
||||
MathQuizEquation(expressionIndices: [0, 1, 2, 3, 4, 5, 6], resultIndex: 8),
|
||||
MathQuizEquation(expressionIndices: [18, 19, 20, 21, 22, 23, 24], resultIndex: 26),
|
||||
MathQuizEquation(expressionIndices: [36, 37, 38, 39, 40, 41, 42], resultIndex: 44),
|
||||
MathQuizEquation(expressionIndices: [54, 55, 56, 57, 58, 59, 60], resultIndex: 62),
|
||||
MathQuizEquation(expressionIndices: [0, 9, 18, 27, 36, 45, 54], resultIndex: 72),
|
||||
MathQuizEquation(expressionIndices: [2, 11, 20, 29, 38, 47, 56], resultIndex: 74),
|
||||
MathQuizEquation(expressionIndices: [4, 13, 22, 31, 40, 49, 58], resultIndex: 76),
|
||||
MathQuizEquation(expressionIndices: [6, 15, 24, 33, 42, 51, 60], resultIndex: 78),
|
||||
],
|
||||
);
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [HELPER] (A, B, C, op) 튜플 생성 (사칙연산 지원)
|
||||
(int, int, int, String) _createEquation(String operators, {int? firstTerm, int maxResult = 9}) {
|
||||
// (이전과 동일)
|
||||
// ( ... _createEquation, _createMultiOpEquation, _calculate는 이전과 동일 ... )
|
||||
(int, int, int, String) _createEquation(String operators, {int? firstTerm, int maxResult = 9}) {
|
||||
final List<String> ops = operators.split(',');
|
||||
final String op = ops[_random.nextInt(ops.length)];
|
||||
int a, b, c;
|
||||
switch (op) {
|
||||
case '+':
|
||||
a = firstTerm ?? _random.nextInt(maxResult - 1) + 1;
|
||||
b = _random.nextInt(maxResult - a) + 1;
|
||||
c = a + b;
|
||||
return (a, b, c, op);
|
||||
case '-':
|
||||
c = firstTerm ?? _random.nextInt(maxResult - 1) + 2;
|
||||
a = _random.nextInt(c - 1) + 1;
|
||||
b = c - a;
|
||||
return (a, b, c, op);
|
||||
case '*':
|
||||
a = firstTerm ?? _random.nextInt(maxResult ~/ 2) + 2;
|
||||
b = _random.nextInt(maxResult ~/ a) + 1;
|
||||
c = a * b;
|
||||
return (a, b, c, op);
|
||||
case '/':
|
||||
b = _random.nextInt(maxResult ~/ 2) + 1;
|
||||
a = _random.nextInt(maxResult ~/ b) + 1;
|
||||
c = a * b;
|
||||
if (c == 0 || a == 0) return _createEquation(operators, firstTerm: firstTerm, maxResult: maxResult);
|
||||
return (a, b, c, op);
|
||||
default:
|
||||
return (1, 1, 2, '+');
|
||||
case '+': a = firstTerm ?? _random.nextInt(maxResult - 1) + 1; b = _random.nextInt(maxResult - a) + 1; c = a + b; return (a, b, c, op);
|
||||
case '-': c = firstTerm ?? _random.nextInt(maxResult - 1) + 2; a = _random.nextInt(c - 1) + 1; b = c - a; return (a, b, c, op);
|
||||
case '*': a = firstTerm ?? _random.nextInt(maxResult ~/ 2) + 2; b = _random.nextInt(maxResult ~/ a) + 1; c = a * b; return (a, b, c, op);
|
||||
case '/': b = _random.nextInt(maxResult ~/ 2) + 1; a = _random.nextInt(maxResult ~/ b) + 1; c = a * b; if (c == 0 || a == 0) return _createEquation(operators, firstTerm: firstTerm, maxResult: maxResult); return (a, b, c, op);
|
||||
default: return (1, 1, 2, '+');
|
||||
}
|
||||
}
|
||||
|
||||
/// [HELPER] 숫자 3개 + 연산자 2개 (우선순위 적용!)
|
||||
(int, int, int, String, String, int) _createMultiOpEquation(String operators) {
|
||||
while(true) {
|
||||
final int a = _random.nextInt(9) + 1;
|
||||
@@ -315,89 +511,25 @@ class MathQuizGenerator {
|
||||
final List<String> ops = operators.split(',');
|
||||
final String op1 = (ops..shuffle(_random)).first;
|
||||
final String op2 = (ops..shuffle(_random)).first;
|
||||
|
||||
final String expression = "$a $op1 $b $op2 $c";
|
||||
if (expression.contains('/')) continue;
|
||||
|
||||
final num resultNum = expression.interpret();
|
||||
final int result = resultNum.toInt();
|
||||
|
||||
if (result == resultNum && result >= -99 && result <= 999) { // [수정] 범위 확장
|
||||
return (a, b, c, op1, op2, result);
|
||||
try {
|
||||
final num resultNum = expression.interpret();
|
||||
final int result = resultNum.toInt();
|
||||
if (result == resultNum && result >= -99 && result <= 999) {
|
||||
return (a, b, c, op1, op2, result);
|
||||
}
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [HELPER] 두 숫자와 연산자로 계산 (실패 시 null 반환)
|
||||
int? _calculate(int a, int b, String op) {
|
||||
switch (op) {
|
||||
case '+': return a + b;
|
||||
case '-': return a - b;
|
||||
case '*': return a * b;
|
||||
case '/':
|
||||
if (b == 0) return null; // 0으로 나누기
|
||||
if (a % b != 0) return null; // 나누어떨어지지 않음
|
||||
return a ~/ b;
|
||||
case '/': if (b == 0) return null; if (a % b != 0) return null; return a ~/ b;
|
||||
}
|
||||
return 0; // 알 수 없는 연산자
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// [신규] 3x3 그리드 템플릿 목록 (8개)
|
||||
List<_GridTemplate> _get3x3Templates() {
|
||||
// [!] 템플릿의 수학적 유효성은 이미지 원본을 따르며, 보장되지 않습니다.
|
||||
return [
|
||||
// 5.53.19.png (top-left)
|
||||
_GridTemplate(gridCells:["5","*","3","-","1","=","17","+"," ","*"," ","-"," ","=","2","*","6","-","7","=","5","*"," ","+"," ","+"," ","=","4","+","1","+","1","=","18","="," ","="," ","="," ","=","21"," ","33"," ","22"," "," "], numberIndices:[0,2,4,14,16,18,28,30,32], operatorIndices:[1,3,7,9,11,15,17,21,23,25,29,31]),
|
||||
// 5.53.19.png (top-right)
|
||||
_GridTemplate(gridCells:["1","+","1","+","5","=","17","/"," ","-"," ","+"," ","=","1","*","3","+","2","=","15","*"," ","+"," ","-"," ","=","6","-","4","+","2","=","0","="," ","="," ","="," ","=","12"," ","12"," ","13"," "," "], numberIndices:[0,2,4,14,16,18,28,30,32], operatorIndices:[1,3,7,9,11,15,17,21,23,25,29,31]),
|
||||
// 5.53.19.png (bottom-left)
|
||||
_GridTemplate(gridCells:["9","+","5","+","5","=","19","/"," ","-"," ","+"," ","=","2","*","3","+","9","=","15","*"," ","+"," ","-"," ","=","6","-","7","+","1","=","0","="," ","="," ","="," ","=","12"," ","9"," ","16"," "," "], numberIndices:[0,2,4,14,16,18,28,30,32], operatorIndices:[1,3,7,9,11,15,17,21,23,25,29,31]),
|
||||
// 5.53.19.png (bottom-right)
|
||||
_GridTemplate(gridCells:["7","*","4","-","9","=","39","*"," ","+"," ","*"," ","=","1","*","1","+","8","=","9","+"," ","*"," ","+"," ","=","3","-","4","+","5","=","4","="," ","="," ","="," ","=","11"," ","34"," ","23"," "," "], numberIndices:[0,2,4,14,16,18,28,30,32], operatorIndices:[1,3,7,9,11,15,17,21,23,25,29,31]),
|
||||
// 5.53.33.png (top-left)
|
||||
_GridTemplate(gridCells:["9","-","5","/","1","=","7","*"," ","-"," ","+"," ","=","8","*","5","-","7","=","27","+"," ","+"," ","+"," ","=","4","+","3","-","7","=","2","="," ","="," ","="," ","=","62"," ","0"," ","12"," "," "], numberIndices:[0,2,4,14,16,18,28,30,32], operatorIndices:[1,3,7,9,11,15,17,21,23,25,29,31]),
|
||||
// 5.53.33.png (top-right)
|
||||
_GridTemplate(gridCells:["8","*","2","+","6","=","16","*"," ","+"," ","/"," ","=","5","*","9","/","3","=","3","+"," ","+"," ","*"," ","=","7","+","1","+","1","=","19","="," ","="," ","="," ","=","9"," ","18"," ","16"," "," "], numberIndices:[0,2,4,14,16,18,28,30,32], operatorIndices:[1,3,7,9,11,15,17,21,23,25,29,31]),
|
||||
// 5.53.33.png (bottom-left)
|
||||
_GridTemplate(gridCells:["1","+","7","+","9","=","17","*"," ","+"," ","-"," ","=","8","/","4","+","4","=","8","+"," ","*"," ","/"," ","=","7","*","3","+","3","=","17","="," ","="," ","="," ","=","13"," ","19"," ","6"," "," "], numberIndices:[0,2,4,14,16,18,28,30,32], operatorIndices:[1,3,7,9,11,15,17,21,23,25,29,31]),
|
||||
// 5.53.33.png (bottom-right)
|
||||
_GridTemplate(gridCells:["1","+","6","-","9","=","6","/"," ","-"," ","/"," ","=","2","-","7","/","1","=","0","-"," ","/"," ","*"," ","=","9","-","5","+","4","=","0","="," ","="," ","="," ","=","0"," ","6"," ","3"," "," "], numberIndices:[0,2,4,14,16,18,28,30,32], operatorIndices:[1,3,7,9,11,15,17,21,23,25,29,31]),
|
||||
];
|
||||
}
|
||||
|
||||
/// [신규] 4x4 그리드 템플릿 목록 (8개)
|
||||
List<_GridTemplate> _get4x4Templates() {
|
||||
// [!] 템플릿의 수학적 유효성은 이미지 원본을 따르며, 보장되지 않습니다.
|
||||
return [
|
||||
// 5.54.51.png (top-left)
|
||||
_GridTemplate(gridCells:["1","*","4","-","2","+","14","=","16","+"," ","*"," ","/"," ","-"," ","=","15","/","5","*","16","+","13","=","61","+"," ","-"," ","+"," ","+"," ","=","3","/","2","+","4","*","7","=","29","*"," ","+"," ","/"," ","*"," ","=","15","+","11","-","8","*","8","=","-38","="," ","="," ","="," ","="," ","=","102"," ","51"," ","54"," ","95"," "," "], numberIndices:[0,2,4,6,18,20,22,24,36,38,40,42,54,56,58,60], operatorIndices:[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,45,47,49,51,53,55,57,59,61,63,65,67,69,71]),
|
||||
// 5.54.51.png (bottom-left)
|
||||
_GridTemplate(gridCells:["8","+","4","*","2","+","15","=","114","-"," ","+"," ","-"," ","-"," ","=","6","/","4","+","3","/","2","=","11","-"," ","-"," ","+"," ","-"," ","=","7","*","3","/","5","-","1","=","0","+"," ","-"," ","*"," ","+"," ","=","12","-","1","*","6","+","11","=","14","="," ","="," ","="," ","="," ","=","1"," ","0"," ","44"," ","18"," "," "], numberIndices:[0,2,4,6,18,20,22,24,36,38,40,42,54,56,58,60], operatorIndices:[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,45,47,49,51,53,55,57,59,61,63,65,67,69,71]),
|
||||
// 5.54.37.png (top-left)
|
||||
_GridTemplate(gridCells:["10","/","2","*","3","+","9","=","24","*"," ","-"," ","*"," ","+"," ","=","2","+","13","*","5","-","7","=","74","+"," ","+"," ","-"," ","+"," ","=","5","*","6","+","1","-","7","=","5","+"," ","-"," ","+"," ","+"," ","=","12","-","11","+","2","*","8","=","49","="," ","="," ","="," ","="," ","=","173"," ","15"," ","17"," ","85"," "," "], numberIndices:[0,2,4,6,18,20,22,24,36,38,40,42,54,56,58,60], operatorIndices:[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,45,47,49,51,53,55,57,59,61,63,65,67,69,71]),
|
||||
// 5.54.37.png (bottom-left)
|
||||
_GridTemplate(gridCells:["9","*","2","+","8","-","1","=","40","/"," ","/"," ","-"," ","*"," ","=","5","+","2","-","13","+","3","=","3","-"," ","*"," ","+"," ","-"," ","=","7","/","1","-","6","+","4","=","4","+"," ","+"," ","*"," ","+"," ","=","16","+","9","-","7","-","10","=","9","="," ","="," ","="," ","="," ","=","5"," ","29"," ","64"," ","13"," "," "], numberIndices:[0,2,4,6,18,20,22,24,36,38,40,42,54,56,58,60], operatorIndices:[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,45,47,49,51,53,55,57,59,61,63,65,67,69,71]),
|
||||
// 5.54.29.png (top-left)
|
||||
_GridTemplate(gridCells:["1","-","5","-","4","+","14","=","8","*"," ","/"," ","*"," ","-"," ","=","7","+","2","*","1","-","11","=","14","-"," ","+"," ","+"," ","-"," ","=","2","/","1","*","7","-","6","=","21","+"," ","+"," ","-"," ","+"," ","=","15","*","10","+","1","+","7","=","173","="," ","="," ","="," ","="," ","=","12"," ","18"," ","21"," ","5"," "," "], numberIndices:[0,2,4,6,18,20,22,24,36,38,40,42,54,56,58,60], operatorIndices:[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,45,47,49,51,53,55,57,59,61,63,65,67,69,71]),
|
||||
// 5.54.29.png (bottom-left)
|
||||
_GridTemplate(gridCells:["9","-","3","-","1","+","13","=","11","*"," ","*"," ","+"," ","+"," ","=","8","*","7","-","9","-","5","=","49","+"," ","+"," ","*"," ","+"," ","=","6","*","5","+","11","-","2","=","41","-"," ","-"," ","-"," ","/"," ","=","15","+","2","-","1","-","4","=","17","="," ","="," ","="," ","="," ","=","71"," ","67"," ","40"," ","18"," "," "], numberIndices:[0,2,4,6,18,20,22,24,36,38,40,42,54,56,58,60], operatorIndices:[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,45,47,49,51,53,55,57,59,61,63,65,67,69,71]),
|
||||
// 5.55.00.png (top-left)
|
||||
_GridTemplate(gridCells:["9","*","8","-","6","+","7","=","141","*"," ","*"," ","/"," ","-"," ","=","2","+","6","*","5","-","10","=","27","-"," ","-"," ","+"," ","-"," ","=","3","+","1","-","3","*","1","=","3","*"," ","+"," ","+"," ","+"," ","=","11","+","7","*","2","+","8","=","25","="," ","="," ","="," ","="," ","=","19"," ","85"," ","20"," ","9"," "," "], numberIndices:[0,2,4,6,18,20,22,24,36,38,40,42,54,56,58,60], operatorIndices:[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,45,47,49,51,53,55,57,59,61,63,65,67,69,71]),
|
||||
// 5.55.00.png (bottom-left)
|
||||
_GridTemplate(gridCells:["4","-","1","-","2","+","14","=","3","+"," ","*"," ","*"," ","-"," ","=","9","-","1","+","3","-","4","=","7","*"," ","/"," ","-"," ","+"," ","=","6","-","1","+","7","+","1","=","17","+"," ","-"," ","+"," ","*"," ","=","8","*","2","+","1","+","16","=","65","="," ","="," ","="," ","="," ","=","38"," ","9"," ","144"," ","178"," "," "], numberIndices:[0,2,4,6,18,20,22,24,36,38,40,42,54,56,58,60], operatorIndices:[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,45,47,49,51,53,55,57,59,61,63,65,67,69,71]),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// [신규] 3x3/4x4 템플릿의 내부 구조
|
||||
class _GridTemplate {
|
||||
final List<String> gridCells;
|
||||
final List<int> numberIndices;
|
||||
final List<int> operatorIndices;
|
||||
|
||||
_GridTemplate({
|
||||
required this.gridCells,
|
||||
required this.numberIndices,
|
||||
required this.operatorIndices,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
// packages/feature_game_mathquiz/lib/models/math_quiz_difficulty.dart
|
||||
import 'package:service_api/service_api.dart';
|
||||
|
||||
/// 빈칸의 유형을 정의
|
||||
enum MathQuizBlankType {
|
||||
numbersOnly, // 숫자만
|
||||
operatorsOnly, // 연산자만
|
||||
numbersAndOperators, // 둘 다
|
||||
}
|
||||
|
||||
/// 퍼즐의 레이아웃 형태를 정의
|
||||
enum MathQuizLayout {
|
||||
singleLine,
|
||||
dualLine,
|
||||
linkedL,
|
||||
gridSquare,
|
||||
}
|
||||
|
||||
/// 'extends GameDifficulty' 추가
|
||||
class MathQuizDifficulty extends GameDifficulty {
|
||||
final int levelIndex;
|
||||
final MathQuizLayout layout;
|
||||
final String operators;
|
||||
final int blankCount;
|
||||
final MathQuizBlankType blankType;
|
||||
final int operationCount;
|
||||
final int puzzleCount;
|
||||
|
||||
const MathQuizDifficulty({
|
||||
required this.levelIndex,
|
||||
required super.name,
|
||||
required super.contextId,
|
||||
required this.layout,
|
||||
required this.operators,
|
||||
required this.blankCount,
|
||||
required this.blankType,
|
||||
required this.operationCount,
|
||||
required this.puzzleCount,
|
||||
});
|
||||
}
|
||||
|
||||
/// 앱 전역에서 사용할 수학 퀴즈 난이도 목록 (19단계)
|
||||
class MathQuizDifficulties {
|
||||
static final List<MathQuizDifficulty> allDifficulties = [
|
||||
// --- 패턴 1: 숫자 2개 (A op B = C) [Lv 1-3] ---
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 1,
|
||||
name: 'Lv. 1: 숫자 2개 (숫자 빈칸)',
|
||||
contextId: 'MATH_L1_OP2_NUM',
|
||||
layout: MathQuizLayout.singleLine,
|
||||
operators: '+,-',
|
||||
blankCount: 1,
|
||||
blankType: MathQuizBlankType.numbersOnly,
|
||||
operationCount: 2,
|
||||
puzzleCount: 10,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 2,
|
||||
name: 'Lv. 2: 숫자 2개 (연산자 빈칸)',
|
||||
contextId: 'MATH_L2_OP2_OP',
|
||||
layout: MathQuizLayout.singleLine,
|
||||
operators: '+,-',
|
||||
blankCount: 1,
|
||||
blankType: MathQuizBlankType.operatorsOnly,
|
||||
operationCount: 2,
|
||||
puzzleCount: 10,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 3,
|
||||
name: 'Lv. 3: 숫자 2개 (사칙연산)',
|
||||
contextId: 'MATH_L3_OP2_ANY',
|
||||
layout: MathQuizLayout.singleLine,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 2,
|
||||
blankType: MathQuizBlankType.numbersAndOperators,
|
||||
operationCount: 2,
|
||||
puzzleCount: 10,
|
||||
),
|
||||
// --- 패턴 2: 숫자 3개 (A op1 B op2 C = D) [Lv 4-6] ---
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 4,
|
||||
name: 'Lv. 4: 숫자 3개 (숫자 빈칸)',
|
||||
contextId: 'MATH_L4_OP3_NUM',
|
||||
layout: MathQuizLayout.singleLine,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 2,
|
||||
blankType: MathQuizBlankType.numbersOnly,
|
||||
operationCount: 3,
|
||||
puzzleCount: 8,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 5,
|
||||
name: 'Lv. 5: 숫자 3개 (연산자 빈칸)',
|
||||
contextId: 'MATH_L5_OP3_OP',
|
||||
layout: MathQuizLayout.singleLine,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 2,
|
||||
blankType: MathQuizBlankType.operatorsOnly,
|
||||
operationCount: 3,
|
||||
puzzleCount: 8,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 6,
|
||||
name: 'Lv. 6: 숫자 3개 (랜덤 빈칸)',
|
||||
contextId: 'MATH_L6_OP3_ANY',
|
||||
layout: MathQuizLayout.singleLine,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 3,
|
||||
blankType: MathQuizBlankType.numbersAndOperators,
|
||||
operationCount: 3,
|
||||
puzzleCount: 8,
|
||||
),
|
||||
// --- 패턴 3: 독립된 2줄 (숫자 4개) [Lv 7-9] ---
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 7,
|
||||
name: 'Lv. 7: 독립 2줄 (숫자)',
|
||||
contextId: 'MATH_L7_OP4_DUAL_NUM',
|
||||
layout: MathQuizLayout.dualLine,
|
||||
operators: '+,-',
|
||||
blankCount: 2,
|
||||
blankType: MathQuizBlankType.numbersOnly,
|
||||
operationCount: 4,
|
||||
puzzleCount: 6,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 8,
|
||||
name: 'Lv. 8: 독립 2줄 (연산자)',
|
||||
contextId: 'MATH_L8_OP4_DUAL_OP',
|
||||
layout: MathQuizLayout.dualLine,
|
||||
operators: '+,-',
|
||||
blankCount: 2,
|
||||
blankType: MathQuizBlankType.operatorsOnly,
|
||||
operationCount: 4,
|
||||
puzzleCount: 6,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 9,
|
||||
name: 'Lv. 9: 독립 2줄 (사칙연산)',
|
||||
contextId: 'MATH_L9_OP4_DUAL_ANY',
|
||||
layout: MathQuizLayout.dualLine,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 3,
|
||||
blankType: MathQuizBlankType.numbersAndOperators,
|
||||
operationCount: 4,
|
||||
puzzleCount: 6,
|
||||
),
|
||||
// --- 패턴 4: 2x2 그리드 (숫자 4개) [Lv 10-12] ---
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 10,
|
||||
name: 'Lv. 10: 2x2 그리드 (숫자)',
|
||||
contextId: 'MATH_L10_OP4_L_NUM',
|
||||
layout: MathQuizLayout.linkedL,
|
||||
operators: '+,-',
|
||||
blankCount: 2,
|
||||
blankType: MathQuizBlankType.numbersOnly,
|
||||
operationCount: 4,
|
||||
puzzleCount: 4,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 11,
|
||||
name: 'Lv. 11: 2x2 그리드 (연산자)',
|
||||
contextId: 'MATH_L11_OP4_L_OP',
|
||||
layout: MathQuizLayout.linkedL,
|
||||
operators: '+,-',
|
||||
blankCount: 2,
|
||||
blankType: MathQuizBlankType.operatorsOnly,
|
||||
operationCount: 4,
|
||||
puzzleCount: 4,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 12,
|
||||
name: 'Lv. 12: 2x2 그리드 (사칙연산)',
|
||||
contextId: 'MATH_L12_OP4_L_ANY',
|
||||
layout: MathQuizLayout.linkedL,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 3,
|
||||
blankType: MathQuizBlankType.numbersAndOperators,
|
||||
operationCount: 4,
|
||||
puzzleCount: 4,
|
||||
),
|
||||
// --- 패턴 5: 3x3 그리드 (숫자 9개) [Lv 13-15] ---
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 13,
|
||||
name: 'Lv. 13: 3x3 그리드 (숫자)',
|
||||
contextId: 'MATH_L13_OP9_NUM',
|
||||
layout: MathQuizLayout.gridSquare,
|
||||
operators: '+,-',
|
||||
blankCount: 3,
|
||||
blankType: MathQuizBlankType.numbersOnly,
|
||||
operationCount: 9,
|
||||
puzzleCount: 3,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 14,
|
||||
name: 'Lv. 14: 3x3 그리드 (연산자)',
|
||||
contextId: 'MATH_L14_OP9_OP',
|
||||
layout: MathQuizLayout.gridSquare,
|
||||
operators: '+,-',
|
||||
blankCount: 3,
|
||||
blankType: MathQuizBlankType.operatorsOnly,
|
||||
operationCount: 9,
|
||||
puzzleCount: 3,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 15,
|
||||
name: 'Lv. 15: 3x3 그리드 (사칙연산)',
|
||||
contextId: 'MATH_L15_OP9_ANY',
|
||||
layout: MathQuizLayout.gridSquare,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 4,
|
||||
blankType: MathQuizBlankType.numbersAndOperators,
|
||||
operationCount: 9,
|
||||
puzzleCount: 3,
|
||||
),
|
||||
// --- 패턴 6: 4x4 그리드 (숫자 16개) [Lv 16-18] ---
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 16,
|
||||
name: 'Lv. 16: 4x4 그리드 (숫자)',
|
||||
contextId: 'MATH_L16_OP16_NUM',
|
||||
layout: MathQuizLayout.gridSquare,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 5,
|
||||
blankType: MathQuizBlankType.numbersOnly,
|
||||
operationCount: 16,
|
||||
puzzleCount: 2,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 17,
|
||||
name: 'Lv. 17: 4x4 그리드 (연산자)',
|
||||
contextId: 'MATH_L17_OP16_OP',
|
||||
layout: MathQuizLayout.gridSquare,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 5,
|
||||
blankType: MathQuizBlankType.operatorsOnly,
|
||||
operationCount: 16,
|
||||
puzzleCount: 2,
|
||||
),
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 18,
|
||||
name: 'Lv. 18: 4x4 그리드 (랜덤)',
|
||||
contextId: 'MATH_L18_OP16_ANY',
|
||||
layout: MathQuizLayout.gridSquare,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 6,
|
||||
blankType: MathQuizBlankType.numbersAndOperators,
|
||||
operationCount: 16,
|
||||
puzzleCount: 2,
|
||||
),
|
||||
// --- [신규] 패턴 7: 4x4 그리드 (고난도) [Lv 19] ---
|
||||
const MathQuizDifficulty(
|
||||
levelIndex: 19,
|
||||
name: 'Lv. 19: 4x4 그리드 (최상)',
|
||||
contextId: 'MATH_L19_OP16_HARD',
|
||||
layout: MathQuizLayout.gridSquare,
|
||||
operators: '+,-,*,/',
|
||||
blankCount: 8,
|
||||
blankType: MathQuizBlankType.numbersAndOperators,
|
||||
operationCount: 16,
|
||||
puzzleCount: 1,
|
||||
),
|
||||
];
|
||||
|
||||
/// 레벨 인덱스로 레벨 정보 찾기
|
||||
static MathQuizDifficulty getLevel(int levelIndex) {
|
||||
if (levelIndex < 1) levelIndex = 1;
|
||||
if (levelIndex > allDifficulties.length) levelIndex = allDifficulties.length;
|
||||
return allDifficulties.firstWhere((level) => level.levelIndex == levelIndex,
|
||||
orElse: () => allDifficulties[0]);
|
||||
}
|
||||
|
||||
/// 랭킹 화면용 맵 (ContextId -> 이름)
|
||||
static Map<String, String> get contextIdToNameMap {
|
||||
return {for (var level in allDifficulties) level.contextId: level.name};
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,36 @@
|
||||
// packages/feature_game_mathquiz/lib/models/math_quiz_models.dart
|
||||
|
||||
/// 개별 빈칸의 타입을 정의
|
||||
enum PuzzleBlankType { number, operator }
|
||||
|
||||
/// 검증해야 할 단일 방정식을 정의
|
||||
class MathQuizEquation {
|
||||
final List<int> expressionIndices;
|
||||
final int resultIndex;
|
||||
|
||||
MathQuizEquation({
|
||||
required this.expressionIndices,
|
||||
required this.resultIndex,
|
||||
});
|
||||
}
|
||||
|
||||
/// 퍼즐 한 판의 데이터 구조
|
||||
class MathQuizPuzzle {
|
||||
/// [수정] 그리드 셀 데이터
|
||||
///
|
||||
/// '?'는 빈칸, ' '는 공백(빈 셀)입니다.
|
||||
///
|
||||
/// 예: ["?", "+", "3", "=", "8"] (5x1 그리드)
|
||||
/// 예: ["?", "+", "2", "=", "5", "+", " ", "+", ... ] (5x5 그리드)
|
||||
final List<String> gridCells;
|
||||
|
||||
/// 그리드의 가로 칸 수 (예: 5)
|
||||
final int gridCrossAxisCount;
|
||||
|
||||
/// 유저가 채워야 할 정답 목록 (순서대로)
|
||||
final List<String> solutions;
|
||||
|
||||
/// 유저에게 제공될 숫자/기호 버튼 옵션
|
||||
final List<String> options;
|
||||
final List<MathQuizEquation> equations;
|
||||
final List<String> solutions;
|
||||
|
||||
/// 빈칸의 타입 목록 (solutions와 1:1 매칭)
|
||||
final List<PuzzleBlankType> blankTypes;
|
||||
|
||||
MathQuizPuzzle({
|
||||
// ❌ puzzleType 삭제
|
||||
required this.gridCells,
|
||||
required this.gridCrossAxisCount,
|
||||
required this.solutions,
|
||||
required this.options,
|
||||
required this.equations,
|
||||
required this.solutions,
|
||||
required this.blankTypes, // 👈 [추가]
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
// packages/feature_game_mathquiz/lib/screens/math_quiz_lobby_screen.dart
|
||||
import 'dart:developer';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
@@ -5,24 +6,27 @@ import 'package:provider/provider.dart';
|
||||
// [C] 공통 서비스 (service_api)
|
||||
import 'package:service_api/service_api.dart';
|
||||
// [A] 공통 UI (feature_common)
|
||||
import 'package:feature_common/feature_common.dart';
|
||||
import 'package:feature_common/feature_common.dart';
|
||||
// [B] 이 패키지 (mathquiz)
|
||||
import 'math_quiz_screen.dart';
|
||||
import '../controllers/math_quiz_controller.dart'; // 👈 [추가] 컨트롤러 임포트
|
||||
import '../controllers/math_quiz_controller.dart';
|
||||
import '../models/math_quiz_difficulty.dart'; // 👈 [추가]
|
||||
|
||||
class MathQuizLobbyScreen extends StatefulWidget {
|
||||
const MathQuizLobbyScreen({ super.key });
|
||||
const MathQuizLobbyScreen({super.key});
|
||||
|
||||
@override
|
||||
State<MathQuizLobbyScreen> createState() => _MathQuizLobbyScreenState();
|
||||
}
|
||||
|
||||
class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
|
||||
int _maxUnlockedLevel = 1;
|
||||
int _maxUnlockedLevel = 1;
|
||||
Map<int, (int, int)> _rankHistory = {};
|
||||
bool _isLoading = false;
|
||||
|
||||
|
||||
late final SessionNotifier _sessionNotifier;
|
||||
late final LobbyHelperService _lobbyHelper;
|
||||
// [🔥 수정] 서비스를 직접 생성 (Provider로 읽지 않음)
|
||||
final PuzzleService _puzzleService = PuzzleService();
|
||||
final IdentityService _identityService = IdentityService();
|
||||
|
||||
@@ -30,61 +34,61 @@ class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
|
||||
void initState() {
|
||||
super.initState();
|
||||
_sessionNotifier = context.read<SessionNotifier>();
|
||||
|
||||
// [🔥 수정] 헬퍼 서비스 초기화 (직접 생성한 서비스 주입)
|
||||
_lobbyHelper = LobbyHelperService(
|
||||
identityService: _identityService,
|
||||
puzzleService: _puzzleService,
|
||||
);
|
||||
|
||||
_loadProgress(forceRefreshRanks: true);
|
||||
}
|
||||
|
||||
/// 랭킹 및 레벨 진행 상황 로드
|
||||
/// [수정됨] 공통 헬퍼를 사용
|
||||
Future<void> _loadProgress({bool forceRefreshRanks = false}) async {
|
||||
// 1. (가벼움) 레벨 정보 새로고침
|
||||
final maxLevel = await _identityService.getMaxUnlockedLevel(gameType: 'MATH_QUIZ');
|
||||
if (mounted) { setState(() { _maxUnlockedLevel = maxLevel; }); }
|
||||
final maxLevel = await _lobbyHelper.loadMaxLevel('MATH_QUIZ');
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_maxUnlockedLevel = maxLevel;
|
||||
});
|
||||
}
|
||||
|
||||
// 2. (무거움) 랭킹 정보 새로고침 (필요할 때만)
|
||||
if (!forceRefreshRanks) return;
|
||||
|
||||
final String? myName = _sessionNotifier.session?.userName;
|
||||
if (myName == null) return;
|
||||
|
||||
if (myName == null) return;
|
||||
|
||||
try {
|
||||
final Map<int, int> oldRankMap = await _identityService.getLastSavedRankMap(gameType: 'MATH_QUIZ');
|
||||
List<Future<List<GameRankDto>>> rankFutures = [];
|
||||
for (final level in MathQuizDifficulties.allDifficulties) {
|
||||
rankFutures.add(_puzzleService.fetchRanks('MATH_QUIZ', level.contextId));
|
||||
final rankHistory = await _lobbyHelper.loadRankHistory<MathQuizDifficulty>(
|
||||
gameType: 'MATH_QUIZ',
|
||||
myName: myName,
|
||||
allLevels: MathQuizDifficulties.allDifficulties,
|
||||
getLevelIndex: (level) => level.levelIndex,
|
||||
);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_rankHistory = rankHistory;
|
||||
});
|
||||
}
|
||||
final List<List<GameRankDto>> allRankResults = await Future.wait(rankFutures);
|
||||
Map<int, int> newRankMapForStorage = {};
|
||||
Map<int, (int, int)> newRankHistoryForState = {};
|
||||
|
||||
for (int i = 0; i < MathQuizDifficulties.allDifficulties.length; i++) {
|
||||
final level = MathQuizDifficulties.allDifficulties[i];
|
||||
final currentRanks = allRankResults[i];
|
||||
final int levelIndex = level.levelIndex;
|
||||
final int oldRank = oldRankMap[levelIndex] ?? 0;
|
||||
int currentRank = 0;
|
||||
int myRankIndex = currentRanks.indexWhere((r) => r.playerName == myName);
|
||||
if (myRankIndex != -1) { currentRank = myRankIndex + 1; }
|
||||
newRankMapForStorage[levelIndex] = currentRank;
|
||||
newRankHistoryForState[levelIndex] = (oldRank, currentRank);
|
||||
}
|
||||
|
||||
await _identityService.saveLastRankMap(newRankMapForStorage, gameType: 'MATH_QUIZ');
|
||||
if (mounted) { setState(() { _rankHistory = newRankHistoryForState; }); }
|
||||
log("수학 퀴즈 랭킹 변동 확인 완료. (유저: $myName)");
|
||||
} catch (e) {
|
||||
log("MathQuizLobbyScreen: 랭킹 확인 실패: $e");
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔽 [수정] 게임 시작 함수
|
||||
/// 🔽 [수정 없음] 게임 시작 함수
|
||||
Future<void> _startGame(MathQuizDifficulty level) async {
|
||||
setState(() { _isLoading = true; });
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
});
|
||||
|
||||
try {
|
||||
final session = _sessionNotifier.session;
|
||||
if (session == null) {
|
||||
throw Exception("세션이 로드되지 않았습니다.");
|
||||
}
|
||||
|
||||
|
||||
// 1. 컨트롤러 생성 및 새 게임 시작 (제너레이터 호출)
|
||||
final controller = MathQuizController();
|
||||
controller.startNewGame(level, session.userId, session.userName);
|
||||
@@ -100,7 +104,7 @@ class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
// 3. 게임에서 돌아오면 레벨 잠금 상태만 새로고침
|
||||
_loadProgress(forceRefreshRanks: false);
|
||||
}
|
||||
@@ -112,48 +116,44 @@ class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() { _isLoading = false; });
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// ... (이하 build 메서드는 이전과 동일) ...
|
||||
context.watch<ThemeNotifier>();
|
||||
context.watch<SessionNotifier>();
|
||||
|
||||
final bool allLevelsUnlocked = _maxUnlockedLevel >= MathQuizDifficulties.allDifficulties.length;
|
||||
context.watch<SessionNotifier>();
|
||||
|
||||
final bool allLevelsUnlocked =
|
||||
_maxUnlockedLevel >= MathQuizDifficulties.allDifficulties.length;
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return CommonGameShell(
|
||||
title: '계산 퀴즈',
|
||||
|
||||
title: '계산 퀴즈',
|
||||
onRankingPressed: () {
|
||||
final List<GameDifficulty> difficulties = MathQuizDifficulties.allDifficulties
|
||||
.map((level) => GameDifficulty(
|
||||
name: level.name,
|
||||
contextId: level.contextId,
|
||||
))
|
||||
.toList();
|
||||
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => RankingScreen(
|
||||
gameType: 'MATH_QUIZ',
|
||||
difficulties: difficulties,
|
||||
initialDifficultyName: MathQuizDifficulties.getLevel(_maxUnlockedLevel).name,
|
||||
difficulties: MathQuizDifficulties.allDifficulties,
|
||||
initialDifficultyName:
|
||||
MathQuizDifficulties.getLevel(_maxUnlockedLevel).name,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
body: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
const double maxContentRatio = 0.6;
|
||||
final double constrainedWidth = (constraints.maxHeight * maxContentRatio) > 500
|
||||
? 500 : (constraints.maxHeight * maxContentRatio);
|
||||
final double constrainedWidth =
|
||||
(constraints.maxHeight * maxContentRatio) > 500
|
||||
? 500
|
||||
: (constraints.maxHeight * maxContentRatio);
|
||||
return Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxWidth: constrainedWidth),
|
||||
@@ -165,14 +165,19 @@ class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
|
||||
child: ListView.builder(
|
||||
itemCount: MathQuizDifficulties.allDifficulties.length,
|
||||
itemBuilder: (context, index) {
|
||||
final MathQuizDifficulty level = MathQuizDifficulties.allDifficulties[index];
|
||||
final bool isUnlocked = allLevelsUnlocked || level.levelIndex <= _maxUnlockedLevel;
|
||||
final (int oldRank, int currentRank) = _rankHistory[level.levelIndex] ?? (0, 0);
|
||||
|
||||
Widget? trailingWidget = isUnlocked ? const Icon(Icons.play_arrow_rounded) : null;
|
||||
final MathQuizDifficulty level =
|
||||
MathQuizDifficulties.allDifficulties[index];
|
||||
final bool isUnlocked = allLevelsUnlocked ||
|
||||
level.levelIndex <= _maxUnlockedLevel;
|
||||
final (int oldRank, int currentRank) =
|
||||
_rankHistory[level.levelIndex] ?? (0, 0);
|
||||
|
||||
Widget? trailingWidget = isUnlocked
|
||||
? const Icon(Icons.play_arrow_rounded)
|
||||
: null;
|
||||
String? subtitleText;
|
||||
Color? subtitleColor;
|
||||
|
||||
|
||||
if (currentRank > 0) {
|
||||
String rankStr = "${currentRank}위";
|
||||
if (oldRank > 0) {
|
||||
@@ -180,45 +185,71 @@ class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
|
||||
if (change > 0) {
|
||||
subtitleText = "$rankStr (▲ $change)";
|
||||
subtitleColor = Colors.green;
|
||||
trailingWidget = const Icon(Icons.arrow_circle_up_rounded, color: Colors.green, size: 28);
|
||||
trailingWidget = const Icon(
|
||||
Icons.arrow_circle_up_rounded,
|
||||
color: Colors.green,
|
||||
size: 28);
|
||||
} else if (change < 0) {
|
||||
subtitleText = "$rankStr (▼ ${change.abs()})";
|
||||
subtitleColor = Colors.red;
|
||||
trailingWidget = const Icon(Icons.arrow_circle_down_rounded, color: Colors.red, size: 28);
|
||||
trailingWidget = const Icon(
|
||||
Icons.arrow_circle_down_rounded,
|
||||
color: Colors.red,
|
||||
size: 28);
|
||||
} else {
|
||||
subtitleText = "$rankStr (유지)";
|
||||
subtitleColor = Colors.grey;
|
||||
trailingWidget = const Icon(Icons.check_circle_outline_rounded, color: Colors.grey, size: 28);
|
||||
trailingWidget = const Icon(
|
||||
Icons.check_circle_outline_rounded,
|
||||
color: Colors.grey,
|
||||
size: 28);
|
||||
}
|
||||
} else {
|
||||
subtitleText = "$rankStr (신규 진입)";
|
||||
subtitleColor = Colors.blue;
|
||||
trailingWidget = const Icon(Icons.new_releases_rounded, color: Colors.blue, size: 28);
|
||||
trailingWidget = const Icon(
|
||||
Icons.new_releases_rounded,
|
||||
color: Colors.blue,
|
||||
size: 28);
|
||||
}
|
||||
} else {
|
||||
if (oldRank > 0) {
|
||||
subtitleText = "랭킹 이탈 (이전 ${oldRank}위)";
|
||||
subtitleColor = Colors.orange;
|
||||
trailingWidget = const Icon(Icons.warning_amber_rounded, color: Colors.orange, size: 28);
|
||||
trailingWidget = const Icon(
|
||||
Icons.warning_amber_rounded,
|
||||
color: Colors.orange,
|
||||
size: 28);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
|
||||
margin: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0, vertical: 4.0),
|
||||
child: ListTile(
|
||||
leading: Icon(
|
||||
isUnlocked ? Icons.lock_open_rounded : Icons.lock_rounded,
|
||||
isUnlocked
|
||||
? Icons.lock_open_rounded
|
||||
: Icons.lock_rounded,
|
||||
color: isUnlocked ? theme.primaryColor : Colors.grey,
|
||||
),
|
||||
title: Text(level.name, style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: isUnlocked ? FontWeight.bold : FontWeight.normal,
|
||||
color: isUnlocked ? theme.textTheme.bodyLarge?.color : Colors.grey,
|
||||
)),
|
||||
title: Text(level.name,
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: isUnlocked
|
||||
? FontWeight.bold
|
||||
: FontWeight.normal,
|
||||
color: isUnlocked
|
||||
? theme.textTheme.bodyLarge?.color
|
||||
: Colors.grey,
|
||||
)),
|
||||
subtitle: subtitleText != null
|
||||
? Text(subtitleText, style: TextStyle(color: subtitleColor, fontWeight: FontWeight.bold))
|
||||
: null,
|
||||
trailing: trailingWidget,
|
||||
? Text(subtitleText,
|
||||
style: TextStyle(
|
||||
color: subtitleColor,
|
||||
fontWeight: FontWeight.bold))
|
||||
: null,
|
||||
trailing: trailingWidget,
|
||||
onTap: isUnlocked && !_isLoading
|
||||
? () => _startGame(level)
|
||||
: null,
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:provider/provider.dart';
|
||||
import 'package:service_api/service_api.dart';
|
||||
import 'package:feature_common/feature_common.dart';
|
||||
import '../controllers/math_quiz_controller.dart';
|
||||
import '../models/math_quiz_difficulty.dart';
|
||||
import '../models/math_quiz_models.dart';
|
||||
|
||||
class MathQuizScreen extends StatefulWidget {
|
||||
@@ -14,24 +15,28 @@ class MathQuizScreen extends StatefulWidget {
|
||||
|
||||
class _MathQuizScreenState extends State<MathQuizScreen> {
|
||||
bool _isDialogShowing = false;
|
||||
|
||||
// ( ... _showGameCompletion 메서드는 이전과 동일 ... )
|
||||
void _showGameCompletion(MathQuizController controller) async {
|
||||
|
||||
// ... ( _showGameCompletion 메서드는 이전과 동일 ... )
|
||||
void _showGameCompletion(MathQuizController controller) async {
|
||||
String formatMathQuizScore(int primary, int? secondary) {
|
||||
final problemCount = primary;
|
||||
final blanksCount = primary;
|
||||
final time = (secondary ?? 0).toString();
|
||||
return '${problemCount}개 (${time}초)';
|
||||
return '총 ${blanksCount}칸 (${time}초)';
|
||||
}
|
||||
|
||||
Future<void> saveMathQuizProgress(String playerName) async {
|
||||
final identityService = IdentityService();
|
||||
final int currentMaxLevel = await identityService.getMaxUnlockedLevel(gameType: 'MATH_QUIZ');
|
||||
final int currentMaxLevel =
|
||||
await identityService.getMaxUnlockedLevel(gameType: 'MATH_QUIZ');
|
||||
if (currentMaxLevel < 99) {
|
||||
if (controller.difficulty.levelIndex >= currentMaxLevel) {
|
||||
int nextLevel = controller.difficulty.levelIndex + 1;
|
||||
if (nextLevel > MathQuizDifficulties.allDifficulties.length) {
|
||||
await identityService.saveMaxUnlockedLevel(99, gameType: 'MATH_QUIZ');
|
||||
await identityService.saveMaxUnlockedLevel(99,
|
||||
gameType: 'MATH_QUIZ');
|
||||
} else {
|
||||
await identityService.saveMaxUnlockedLevel(nextLevel, gameType: 'MATH_QUIZ');
|
||||
await identityService.saveMaxUnlockedLevel(nextLevel,
|
||||
gameType: 'MATH_QUIZ');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,11 +46,11 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => GameCompletionScreen(
|
||||
args: GameResultArgs(
|
||||
args: GameResultArgs(
|
||||
gameType: 'MATH_QUIZ',
|
||||
contextId: controller.difficulty.contextId,
|
||||
primaryScore: controller.puzzle.solutions.length,
|
||||
secondaryScore: controller.secondsElapsed,
|
||||
primaryScore: controller.totalBlanksFilled,
|
||||
secondaryScore: controller.secondsElapsed,
|
||||
userId: controller.userId,
|
||||
userName: controller.userName,
|
||||
scoreFormatter: formatMathQuizScore,
|
||||
@@ -73,14 +78,30 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(controller.difficulty.name),
|
||||
title: Text('Lv. ${controller.difficulty.levelIndex}'),
|
||||
actions: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 20.0),
|
||||
child: Center(
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: _buildTriesWidget(controller.remainingTries),
|
||||
),
|
||||
),
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: Text(
|
||||
'${controller.currentPuzzleIndex + 1} / ${controller.totalPuzzlesInLevel}',
|
||||
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
),
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(right: 20.0),
|
||||
child: Text(
|
||||
'${(controller.secondsElapsed ~/ 60).toString().padLeft(2, '0')}:${(controller.secondsElapsed % 60).toString().padLeft(2, '0')}',
|
||||
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
style:
|
||||
const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -99,15 +120,27 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
/// 🔽 세로 모드 레이아웃
|
||||
Widget _buildPortraitLayout(BuildContext context, MathQuizController controller) {
|
||||
Widget _buildTriesWidget(int tries) {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: List.generate(3, (index) {
|
||||
return Icon(
|
||||
index < tries ? Icons.favorite : Icons.favorite_border,
|
||||
color: Colors.redAccent,
|
||||
size: 24,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPortraitLayout(
|
||||
BuildContext context, MathQuizController controller) {
|
||||
return Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
// [수정] _buildPuzzleGrid를 항상 호출
|
||||
child: _buildPuzzleGrid(context, controller),
|
||||
),
|
||||
),
|
||||
@@ -117,38 +150,33 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
/// 🔽 가로 모드 레이아웃
|
||||
Widget _buildLandscapeLayout(BuildContext context, MathQuizController controller) {
|
||||
Widget _buildLandscapeLayout(
|
||||
BuildContext context, MathQuizController controller) {
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 6, // 방정식 영역
|
||||
flex: 6,
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
// [수정] _buildPuzzleGrid를 항상 호출
|
||||
child: _buildPuzzleGrid(context, controller),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
flex: 4, // 키패드 영역
|
||||
flex: 4,
|
||||
child: _buildKeypad(context, controller),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// ❌ [삭제] _buildEquationList 메서드 삭제
|
||||
|
||||
/// [수정] _buildEquationGrid -> _buildPuzzleGrid
|
||||
/// (모든 퍼즐을 그리는 유일한 빌더)
|
||||
Widget _buildPuzzleGrid(BuildContext context, MathQuizController controller) {
|
||||
final puzzle = controller.puzzle;
|
||||
final userAnswers = controller.userAnswers;
|
||||
final int crossAxisCount = puzzle.gridCrossAxisCount;
|
||||
|
||||
int blankIndex = 0;
|
||||
|
||||
int blankIndex = 0;
|
||||
|
||||
return GridView.builder(
|
||||
shrinkWrap: true,
|
||||
@@ -159,26 +187,32 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final String part = puzzle.gridCells[index];
|
||||
|
||||
|
||||
if (part == "?") {
|
||||
// 빈칸일 경우
|
||||
final int currentBlankIndex = blankIndex;
|
||||
blankIndex++;
|
||||
return _buildBlankBox(
|
||||
context,
|
||||
controller,
|
||||
currentBlankIndex,
|
||||
userAnswers[currentBlankIndex],
|
||||
(currentBlankIndex < userAnswers.length)
|
||||
? userAnswers[currentBlankIndex]
|
||||
: null,
|
||||
);
|
||||
} else if (part == " ") {
|
||||
// " " (빈 공간)
|
||||
return Container();
|
||||
} else {
|
||||
// 숫자나 기호일 경우
|
||||
return Center(
|
||||
child: Text(
|
||||
part,
|
||||
style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
|
||||
child: FittedBox(
|
||||
fit: BoxFit.contain,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4.0),
|
||||
child: Text(
|
||||
part,
|
||||
style: const TextStyle(
|
||||
fontSize: 32, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -186,38 +220,55 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
/// [수정] _buildBlankBox (isGrid 파라미터 삭제)
|
||||
Widget _buildBlankBox(BuildContext context, MathQuizController controller, int index, String? value) {
|
||||
Widget _buildBlankBox(BuildContext context, MathQuizController controller,
|
||||
int index, String? value) {
|
||||
final theme = Theme.of(context);
|
||||
final bool isSelected = (controller.selectedBlankIndex == index);
|
||||
final bool isWrong = controller.isWrongAnswer;
|
||||
final bool isRevealing = controller.isRevealingAnswer;
|
||||
|
||||
Color borderColor;
|
||||
Color textColor;
|
||||
|
||||
if (isRevealing) {
|
||||
borderColor = theme.colorScheme.primary;
|
||||
textColor = theme.colorScheme.primary;
|
||||
} else if (isWrong) {
|
||||
borderColor = theme.colorScheme.error;
|
||||
textColor = theme.colorScheme.onSurfaceVariant;
|
||||
} else if (isSelected) {
|
||||
borderColor = theme.colorScheme.primary;
|
||||
textColor = theme.colorScheme.onSurfaceVariant;
|
||||
} else {
|
||||
borderColor = Colors.transparent;
|
||||
textColor = theme.colorScheme.onSurfaceVariant;
|
||||
}
|
||||
|
||||
// [수정] 그리드 셀의 크기는 GridView가 결정하므로
|
||||
// AspectRatio를 사용해 1:1 비율 유지
|
||||
return AspectRatio(
|
||||
aspectRatio: 1 / 1,
|
||||
child: GestureDetector(
|
||||
onTap: () => controller.onBlankTapped(index),
|
||||
child: Container(
|
||||
margin: const EdgeInsets.all(4.0), // 그리드/리스트 공통 여백
|
||||
margin: const EdgeInsets.all(4.0),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceVariant,
|
||||
border: Border.all(
|
||||
color: isSelected ? theme.colorScheme.primary : Colors.transparent,
|
||||
color: borderColor,
|
||||
width: 3,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Center(
|
||||
// [수정] 폰트 크기를 FittedBox로 자동 조절
|
||||
child: FittedBox(
|
||||
fit: BoxFit.contain,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4.0),
|
||||
child: Text(
|
||||
value ?? '',
|
||||
value ?? '',
|
||||
style: TextStyle(
|
||||
fontSize: 32,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
color: textColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -228,13 +279,32 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
/// 2. 키패드 UI 빌더
|
||||
/// [🔥 수정됨] 키패드 UI 빌더 (동적 필터링)
|
||||
Widget _buildKeypad(BuildContext context, MathQuizController controller) {
|
||||
// ... (이하 키패드 로직은 동일) ...
|
||||
final puzzle = controller.puzzle;
|
||||
final theme = Theme.of(context);
|
||||
final bool isDisabled = controller.isRevealingAnswer;
|
||||
|
||||
final PuzzleBlankType? selectedType = controller.currentSelectedBlankType;
|
||||
|
||||
// [🔥 최종 확인] 헬퍼 함수
|
||||
bool isOperator(String val) => ['/', '*', '-', '+'].contains(val);
|
||||
bool isNumber(String val) => int.tryParse(val) != null;
|
||||
|
||||
// [🔥 최종 수정] 타입에 따라 옵션 필터링
|
||||
List<String> availableOptions = [];
|
||||
if (selectedType == PuzzleBlankType.number) {
|
||||
// 숫자가 필요하면 숫자만 필터링
|
||||
availableOptions = puzzle.options.where((opt) => isNumber(opt)).toList();
|
||||
} else if (selectedType == PuzzleBlankType.operator) {
|
||||
// 연산자가 필요하면 연산자만 필터링
|
||||
availableOptions = puzzle.options.where((opt) => isOperator(opt)).toList();
|
||||
}
|
||||
|
||||
final int totalButtonCount = availableOptions.length + 1; // 필터링된 옵션 + 지우기
|
||||
|
||||
return Container(
|
||||
// ... (GridView.builder 이하 로직은 동일) ...
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.scaffoldBackgroundColor,
|
||||
@@ -255,19 +325,18 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
|
||||
mainAxisSpacing: 8,
|
||||
crossAxisSpacing: 8,
|
||||
),
|
||||
itemCount: puzzle.options.length + 1, // 옵션 + 지우기 버튼
|
||||
itemCount: totalButtonCount,
|
||||
itemBuilder: (context, index) {
|
||||
|
||||
if (index == puzzle.options.length) {
|
||||
if (index == availableOptions.length) {
|
||||
return FilledButton.tonal(
|
||||
onPressed: () => controller.onClearTapped(),
|
||||
onPressed: isDisabled ? null : () => controller.onClearTapped(),
|
||||
child: const Icon(Icons.backspace_outlined),
|
||||
);
|
||||
}
|
||||
|
||||
final String option = puzzle.options[index];
|
||||
|
||||
final String option = availableOptions[index];
|
||||
return FilledButton(
|
||||
onPressed: () => controller.onOptionTapped(option),
|
||||
onPressed: isDisabled ? null : () => controller.onOptionTapped(option),
|
||||
child: Text(
|
||||
option,
|
||||
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
|
||||
Reference in New Issue
Block a user