Games
Мини-игры для геймификации обучения.
Структура
src/features/games/
├── api/
│ ├── queries.ts # fetchGameHistory(), fetchLatestLearningStyle()
│ └── mutations.ts # saveGameResult()
├── hooks/
│ ├── use-save-game-result.ts
│ └── use-game-history.ts
├── components/
│ ├── memory-cards/
│ │ └── card-grid.tsx # Сетка карточек
│ ├── pattern-sequence/
│ │ ├── color-button.tsx # Цветная кнопка
│ │ └── button-grid.tsx # Сетка кнопок
│ ├── learning-style/
│ │ ├── question-card.tsx # Вопрос VARK
│ │ └── result-display.tsx # Результаты
│ ├── topic-flashcards/
│ │ ├── flashcard.tsx # Карточка с flip анимацией
│ │ └── flashcard-game.tsx # Игровой процесс
│ ├── topic-typing/
│ │ ├── typing-game.tsx # Игра печати
│ │ ├── typing-input.tsx # Поле ввода
│ │ └── typing-stats.tsx # Статистика WPM/точность
│ └── shared/
│ ├── game-header.tsx
│ ├── score-display.tsx
│ └── game-complete-modal.tsx
├── constants.ts # CARD_SYMBOLS, PATTERN_COLORS, VARK_QUESTIONS
├── utils/
│ ├── calculate-vark.ts
│ └── topic-content.ts # Генерация контента для topic-игр
├── types.ts
└── index.ts
Игры
1. Memory Cards
Найти пары одинаковых карточек.
// Zustand store
interface MemoryCardsStore {
cards: Card[];
flippedIndices: number[];
matchedPairs: number[];
moves: number;
initGame: (difficulty: 'easy' | 'medium' | 'hard') => void;
flipCard: (index: number) => void;
checkMatch: () => void;
reset: () => void;
}
Механика:
- Генерируются пары карточек с символами
- Карточки перемешиваются
- Игрок переворачивает по 2 карточки
- При совпадении — карточки остаются открытыми
- Цель — найти все пары за минимум ходов
// components/memory-cards/flip-card.tsx
function FlipCard({ symbol, isFlipped, onPress }) {
const rotation = useSharedValue(0);
useEffect(() => {
rotation.value = withSpring(isFlipped ? 180 : 0);
}, [isFlipped]);
const frontStyle = useAnimatedStyle(() => ({
transform: [{ rotateY: `${rotation.value}deg` }],
backfaceVisibility: 'hidden',
}));
const backStyle = useAnimatedStyle(() => ({
transform: [{ rotateY: `${rotation.value + 180}deg` }],
backfaceVisibility: 'hidden',
}));
return (
<Pressable onPress={onPress}>
<Animated.View style={frontStyle}>
<Text>{symbol}</Text>
</Animated.View>
<Animated.View style={[backStyle, StyleSheet.absoluteFill]}>
<Text>?</Text>
</Animated.View>
</Pressable>
);
}
2. Pattern Sequence
Запомнить и повторить последовательность цветов.
// Zustand store
interface PatternSequenceStore {
sequence: number[];
playerSequence: number[];
level: number;
isShowingPattern: boolean;
addToSequence: () => void;
playerPress: (color: number) => void;
showPattern: () => Promise<void>;
reset: () => void;
}
Механика:
- Показывается последовательность цветов (подсвечиваются кнопки)
- Игрок повторяет последовательность
- При успехе — добавляется ещё один цвет
- При ошибке — игра заканчивается
// Показ паттерна
async function showPattern() {
setIsShowingPattern(true);
for (const colorIndex of sequence) {
await highlightButton(colorIndex, 500);
await delay(200);
}
setIsShowingPattern(false);
}
3. Learning Style Quiz (VARK)
Определение стиля обучения по методологии VARK.
// Zustand store
interface LearningStyleStore {
currentQuestion: number;
answers: Record<number, string>;
result: VARKResult | null;
answerQuestion: (answer: string) => void;
calculateResult: () => void;
reset: () => void;
}
interface VARKResult {
visual: number;
aural: number;
read: number;
kinesthetic: number;
dominant: 'V' | 'A' | 'R' | 'K';
}
VARK категории:
- V (Visual) — Визуальный: диаграммы, графики, видео
- A (Aural) — Аудиальный: лекции, обсуждения
- R (Read/Write) — Чтение/письмо: тексты, заметки
- K (Kinesthetic) — Кинестетический: практика, эксперименты
// utils/calculate-vark.ts
export function calculateVARK(answers: Record<number, string>): VARKResult {
const scores = { V: 0, A: 0, R: 0, K: 0 };
Object.values(answers).forEach(answer => {
scores[answer as keyof typeof scores]++;
});
const dominant = Object.entries(scores)
.sort(([, a], [, b]) => b - a)[0][0] as VARKResult['dominant'];
return {
visual: scores.V,
aural: scores.A,
read: scores.R,
kinesthetic: scores.K,
dominant,
};
}
4. Topic Flashcards
Изучение терминов из уроков через карточки.
// Zustand store
interface FlashcardsStore {
cards: Flashcard[];
currentIndex: number;
isFlipped: boolean;
knownCards: string[];
initGame: (lessonId: string) => void;
flipCard: () => void;
nextCard: () => void;
markAsKnown: () => void;
reset: () => void;
}
interface Flashcard {
id: string;
term: string;
definition: string;
}
Механика:
- Карточки генерируются из контента урока (ключевые термины)
- Показывается термин, по тапу — переворот с определением
- Свайп вправо — "знаю", влево — "повторить"
- Карточки "повторить" возвращаются в конец колоды
5. Topic Typing
Тренировка печати текста из уроков.
// Zustand store
interface TypingGameStore {
text: string;
userInput: string;
startTime: number | null;
errors: number;
wpm: number;
accuracy: number;
isComplete: boolean;
initGame: (lessonId: string) => void;
handleInput: (char: string) => void;
calculateStats: () => void;
reset: () => void;
}
Механика:
- Текст берётся из контента урока
- Пользователь печатает текст посимвольно
- Ошибки подсвечиваются красным
- По завершении показывается WPM (слов в минуту) и точность
// components/topic-typing/typing-stats.tsx
function TypingStats({ wpm, accuracy, errors }) {
return (
<View className="flex-row justify-around">
<StatItem label="WPM" value={wpm} />
<StatItem label="Точность" value={`${accuracy}%`} />
<StatItem label="Ошибки" value={errors} />
</View>
);
}
Сохранение результатов
// hooks/use-save-game-result.ts
export function useSaveGameResult() {
const { mutate } = useMutation({
mutationFn: saveGameResult,
onSuccess: (data) => {
// Начислить XP
queryClient.invalidateQueries(['gamification']);
},
});
return mutate;
}
// Использование
function GameCompleteModal({ game, score }) {
const saveResult = useSaveGameResult();
useEffect(() => {
saveResult({
gameType: game,
score,
completedAt: new Date(),
});
}, []);
}
Экраны
| Экран | Путь | Описание |
|---|---|---|
| Games Hub | (app)/(tabs)/games | Выбор игры |
| Memory Cards | (app)/games/memory-cards | Игра Memory |
| Pattern Sequence | (app)/games/pattern-sequence | Игра Pattern |
| Learning Style | (app)/games/learning-style | VARK тест |
| Flashcards | (app)/games/flashcards | Карточки по теме урока |
| Typing | (app)/games/typing | Печать текста из урока |
Query Keys
['games', 'history'] // История игр
['games', 'learning-style'] // Последний результат VARK