logic done
This commit is contained in:
@@ -19,9 +19,11 @@ function Matching({ tasks, index }: ComponentProps) {
|
|||||||
const answers: boolean[] = tasks.map((item) => Boolean(item.answer));
|
const answers: boolean[] = tasks.map((item) => Boolean(item.answer));
|
||||||
const items: string[] = tasks.map((item) => String(item.answer));
|
const items: string[] = tasks.map((item) => String(item.answer));
|
||||||
const arr = useSelector((state: RootState) => state.quiz.userAnswers[index]);
|
const arr = useSelector((state: RootState) => state.quiz.userAnswers[index]);
|
||||||
|
// const correctAnswers = useSelector((state: RootState) => state.quiz.correctAnswers[index]);
|
||||||
|
const questions = useSelector((state: RootState) => state.quiz.questions[index]);
|
||||||
const isDisabled = useSelector((state: RootState) => state.quiz.isTestingDone);
|
const isDisabled = useSelector((state: RootState) => state.quiz.isTestingDone);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
dispatch(addList({ index, items: items, answers: answers, quizType: "M" }));
|
dispatch(addList({ index, items: items,questions:tasks.map((item) => String(item.question)), answers: answers, quizType: "M" }));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -29,19 +31,19 @@ function Matching({ tasks, index }: ComponentProps) {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|
||||||
const handleCheckboxAction = (checkboxIndex: number) => (event: ChangeEvent<HTMLInputElement, Element>, checked: boolean) => {
|
const handleCheckboxAction = (checkboxIndex: number) => (_: ChangeEvent<HTMLInputElement, Element>, checked: boolean) => {
|
||||||
let answersCopy = [ ...arr ];
|
let answersCopy = arr.map((x)=>(Boolean(x)));
|
||||||
answersCopy[checkboxIndex] = checked;
|
answersCopy[checkboxIndex] = checked;
|
||||||
dispatch(setCheckedItems({ index, items: answersCopy }));
|
dispatch(setCheckedItems({ index, items: answersCopy }));
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log(arr);
|
// console.log(arr);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Grid container spacing={2}>
|
<Grid container spacing={2}>
|
||||||
<Grid size={12}>
|
<Grid size={12}>
|
||||||
<List>
|
<List>
|
||||||
{tasks.map((item, itemIndex) => (
|
{tasks.map((_, itemIndex) => (
|
||||||
<ListItem key={itemIndex}>
|
<ListItem key={itemIndex}>
|
||||||
<ListItemButton
|
<ListItemButton
|
||||||
sx={{
|
sx={{
|
||||||
@@ -49,7 +51,7 @@ function Matching({ tasks, index }: ComponentProps) {
|
|||||||
borderRadius: '5px',
|
borderRadius: '5px',
|
||||||
textAlign: 'right',
|
textAlign: 'right',
|
||||||
}}>
|
}}>
|
||||||
<ListItemText primary={item.question} />
|
<ListItemText primary={arr == undefined ? "loading": questions[itemIndex]} />
|
||||||
<Checkbox
|
<Checkbox
|
||||||
onChange={isDisabled ? (..._) => { _ } : handleCheckboxAction(itemIndex)}
|
onChange={isDisabled ? (..._) => { _ } : handleCheckboxAction(itemIndex)}
|
||||||
checked={Boolean(arr == undefined ? false : arr[itemIndex])}
|
checked={Boolean(arr == undefined ? false : arr[itemIndex])}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ function Matching({ tasks, index }: ComponentProps) {
|
|||||||
const answers: string[] = tasks.map((item) => String(item.answer));
|
const answers: string[] = tasks.map((item) => String(item.answer));
|
||||||
// Добавляем список ответов очередного задания в хранилище
|
// Добавляем список ответов очередного задания в хранилище
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
dispatch(addList({ index, items: answers, answers:answers, quizType: "M" }));
|
dispatch(addList({ index, items: answers, answers:answers, questions:tasks.map((item) => String(item.question)), quizType: "M" }));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -11,27 +11,40 @@ import { useDispatch } from 'react-redux';
|
|||||||
import { mixUp, startTesting, stopTesting } from './quizSlice';
|
import { mixUp, startTesting, stopTesting } from './quizSlice';
|
||||||
|
|
||||||
function QuizStats() {
|
function QuizStats() {
|
||||||
|
let correctAnswers = useSelector((state: RootState) => state.quiz.correctAnswers);
|
||||||
|
const userAnswers = useSelector((state: RootState) => state.quiz.userAnswers);
|
||||||
|
|
||||||
const correctCount = (index: number): number => {
|
const correctCount = (index: number): number => {
|
||||||
let quiz = useSelector((state: RootState) => state.quiz);
|
|
||||||
let state = store.getState();
|
let state = store.getState();
|
||||||
if (state.quiz.correctAnswers.length <= index) {
|
if (state.quiz.correctAnswers.length <= index) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
return quiz.userAnswers[index].reduce((prev, answ, i) => prev + Number(quiz.correctAnswers[index][i] === answ), 0);
|
return userAnswers[index].reduce((prev, answ, i) => prev + Number(correctAnswers[index][i] === answ), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
const quizPartText = (counter: number, len: number): string => {
|
const counts = userAnswers.map((_,index)=>correctCount(index));
|
||||||
|
const questionCounts = userAnswers.map((answers)=>answers.length);
|
||||||
|
|
||||||
|
const total= counts.reduce((x,c)=>c+x,0);
|
||||||
|
const totalQuestionCount= questionCounts.reduce((x,c)=>c+x,0);
|
||||||
|
|
||||||
|
const donePercentage = Math.round(total/totalQuestionCount*100*100)/100;
|
||||||
|
|
||||||
|
const quizPartText = (counter: number, len: number, taskIndex:number) => {
|
||||||
if (counter == len) {
|
if (counter == len) {
|
||||||
return "все ответы верные"
|
return <Typography key={taskIndex}>Задание {taskIndex+1}: все ответы верные</Typography>
|
||||||
}
|
}
|
||||||
return `верно ${counter}/${len}`
|
return <Typography key={taskIndex}>Задание {taskIndex+1}: верно {counter}/{len}</Typography>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container sx={{ margin: "auto" }}>
|
<Container sx={{ margin: "auto", d:"flex",flexDirection:"column" }}>
|
||||||
<h3>Результаты теста</h3>
|
<h2>Результаты теста</h2>
|
||||||
{/* <Typography>Задание 1: {checkTask(0)}</Typography> */}
|
{
|
||||||
{/* <Typography>Задание 2: {checkTask(1)}</Typography> */}
|
counts.map((count,idx)=>quizPartText(count,questionCounts[idx],idx))
|
||||||
|
}
|
||||||
|
<h3>Итого {donePercentage}% Верно</h3>
|
||||||
</Container>
|
</Container>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -61,19 +74,19 @@ function Quiz() {
|
|||||||
</Typography>
|
</Typography>
|
||||||
{[
|
{[
|
||||||
|
|
||||||
<Matching index={index} tasks={item.tasks} />,
|
<Matching index={index} tasks={item.tasks} key={index}/>,
|
||||||
|
|
||||||
<Sorting index={index} tasks={item.tasks} />,
|
<Sorting index={index} tasks={item.tasks} key={index}/>,
|
||||||
|
|
||||||
<Choosing index={index} tasks={item.tasks} />
|
<Choosing index={index} tasks={item.tasks} key={index}/>
|
||||||
|
|
||||||
][(["M", "S", "C"].indexOf(item.type))]}
|
][(["M", "S", "C"].indexOf(item.type))]}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
))}
|
))}
|
||||||
<Box sx={{ display: 'flex', justifyContent: 'space-around' }}>
|
<Box sx={{ display: 'flex', justifyContent: 'space-around' }}>
|
||||||
<Button onClick={checkQuiz} variant="contained">Проверить</Button>
|
<Button onClick={checkQuiz} variant="contained">Check</Button>
|
||||||
<Button onClick={resetQuiz} variant="contained">Начать снова</Button>
|
<Button onClick={resetQuiz} variant="contained">Reset</Button>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{displayingResults && <QuizStats />}
|
{displayingResults && <QuizStats />}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ function Matching({ tasks, index }: ComponentProps) {
|
|||||||
const answers: string[] = tasks.map((item) => String(item.answer));
|
const answers: string[] = tasks.map((item) => String(item.answer));
|
||||||
// Добавляем список ответов очередного задания в хранилище
|
// Добавляем список ответов очередного задания в хранилище
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
dispatch(addList({ index, items: answers, answers:answers, quizType: "M" }));
|
dispatch(addList({ index, items: answers, answers:answers,questions:tasks.map((item) => String(item.question)), quizType: "M" }));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ function shuffle<T>(array: Array<T>): Array<T> {
|
|||||||
|
|
||||||
interface QuizState {
|
interface QuizState {
|
||||||
userAnswers: (string | boolean)[][]; // хранит перемещаемые элементы каждого списка ответов
|
userAnswers: (string | boolean)[][]; // хранит перемещаемые элементы каждого списка ответов
|
||||||
|
questions: string[][];
|
||||||
correctAnswers: (string | boolean)[][];// ответы для вопрсов, в случае с matching просто правильная последоавтельность, для sorting аналогично, для choosе последоватеьность boolean
|
correctAnswers: (string | boolean)[][];// ответы для вопрсов, в случае с matching просто правильная последоавтельность, для sorting аналогично, для choosе последоватеьность boolean
|
||||||
quizTypes: Array<"M" | "S" | "C">;
|
quizTypes: Array<"M" | "S" | "C">;
|
||||||
isTestingDone: boolean// запрет на взаимодействие с квизом после окончания тестирования, чтобю юзер не наглел
|
isTestingDone: boolean// запрет на взаимодействие с квизом после окончания тестирования, чтобю юзер не наглел
|
||||||
@@ -29,6 +30,7 @@ const initialState: QuizState = {
|
|||||||
userAnswers: [],
|
userAnswers: [],
|
||||||
correctAnswers: [],
|
correctAnswers: [],
|
||||||
quizTypes: [],
|
quizTypes: [],
|
||||||
|
questions:[],
|
||||||
isTestingDone: false,
|
isTestingDone: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -36,8 +38,9 @@ const listsSlice = createSlice({
|
|||||||
name: 'lists',
|
name: 'lists',
|
||||||
initialState,
|
initialState,
|
||||||
reducers: {
|
reducers: {
|
||||||
addList: (state, action: PayloadAction<{ index: number; items: string[]; answers: (string|boolean)[]; quizType : "S" | "M" | "C"}>) => {
|
addList: (state, action: PayloadAction<{ index: number; items: string[]; questions: string[]; answers: (string|boolean)[]; quizType : "S" | "M" | "C"}>) => {
|
||||||
const { index, items,answers,quizType} = action.payload;
|
const { index, items,questions,answers,quizType} = action.payload;
|
||||||
|
state.questions.splice(index, 1, questions);
|
||||||
state.userAnswers.splice(index, 1, items); // с нулём создаётся по 2 экземпляра, видно в отладке
|
state.userAnswers.splice(index, 1, items); // с нулём создаётся по 2 экземпляра, видно в отладке
|
||||||
state.quizTypes.splice(index, 1, quizType); //
|
state.quizTypes.splice(index, 1, quizType); //
|
||||||
state.correctAnswers.splice(index, 1, answers);
|
state.correctAnswers.splice(index, 1, answers);
|
||||||
@@ -49,7 +52,7 @@ const listsSlice = createSlice({
|
|||||||
state.userAnswers[index] = items; // обновляем конкретный список
|
state.userAnswers[index] = items; // обновляем конкретный список
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
setCheckedItems: (state, action: PayloadAction<{ index: number; items: (string|boolean)[] }>) => {
|
setCheckedItems: (state, action: PayloadAction<{ index: number; items: boolean[] }>) => {
|
||||||
const { index, items } = action.payload;
|
const { index, items } = action.payload;
|
||||||
if (index >= 0 && index < state.userAnswers.length) {
|
if (index >= 0 && index < state.userAnswers.length) {
|
||||||
state.userAnswers[index] = items; // обновляем конкретный список
|
state.userAnswers[index] = items; // обновляем конкретный список
|
||||||
@@ -58,7 +61,11 @@ const listsSlice = createSlice({
|
|||||||
mixUp: (state) => {
|
mixUp: (state) => {
|
||||||
state.userAnswers = state.userAnswers.map((list,index) => {
|
state.userAnswers = state.userAnswers.map((list,index) => {
|
||||||
if(typeof(state.correctAnswers[index][0])==="boolean"){
|
if(typeof(state.correctAnswers[index][0])==="boolean"){
|
||||||
return list.map(()=>false);
|
list.map(()=>false);
|
||||||
|
let indexes = shuffle( list.map((_,idx)=>idx));
|
||||||
|
state.correctAnswers[index]=state.correctAnswers[index].map((_,i,arr)=>arr[indexes[i]])
|
||||||
|
state.questions[index]=state.questions[index].map((_,i,arr)=>arr[indexes[i]])
|
||||||
|
return list.map(()=>false)
|
||||||
}
|
}
|
||||||
return shuffle<string|boolean>(list);
|
return shuffle<string|boolean>(list);
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -68,23 +68,23 @@ export const quiz: tQuizzes = [
|
|||||||
"title": "Вопрос 3 Выбирай",
|
"title": "Вопрос 3 Выбирай",
|
||||||
"tasks": [
|
"tasks": [
|
||||||
{
|
{
|
||||||
"question": "123",
|
"question": "да",
|
||||||
"answer": true
|
"answer": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"question": "456",
|
"question": "нет",
|
||||||
"answer": false
|
"answer": false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"question": "789",
|
"question": "да1",
|
||||||
"answer": true
|
"answer": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"question": "101112",
|
"question": "нет1",
|
||||||
"answer": false
|
"answer": false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"question": "131415",
|
"question": "да2",
|
||||||
"answer": true
|
"answer": true
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|||||||
Reference in New Issue
Block a user