lab 8 done

This commit is contained in:
2026-04-24 12:16:17 +10:00
parent 7684b8d705
commit c37b24ec38
8 changed files with 118 additions and 14 deletions

View File

@@ -16,6 +16,7 @@
"@mui/material": "^9.0.0", "@mui/material": "^9.0.0",
"@mui/x-charts": "^9.0.1", "@mui/x-charts": "^9.0.1",
"@mui/x-data-grid": "^9.0.1", "@mui/x-data-grid": "^9.0.1",
"@redux-devtools/extension": "^4.0.0",
"@reduxjs/toolkit": "^2.11.2", "@reduxjs/toolkit": "^2.11.2",
"react": "^19.2.4", "react": "^19.2.4",
"react-dom": "^19.2.4", "react-dom": "^19.2.4",
@@ -1206,6 +1207,15 @@
"url": "https://opencollective.com/popperjs" "url": "https://opencollective.com/popperjs"
} }
}, },
"node_modules/@redux-devtools/extension": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@redux-devtools/extension/-/extension-4.0.0.tgz",
"integrity": "sha512-pLIzgo5MvqdDLe5D1pzHLgmr8THra/DOyRf5MvOEPZnKKDn6RhFbNSS5oXZ3Cal0cpx08kx7sR6zD8QgoXEnZA==",
"license": "MIT",
"peerDependencies": {
"redux": "^3.1.0 || ^4.0.0 || ^5.0.0"
}
},
"node_modules/@reduxjs/toolkit": { "node_modules/@reduxjs/toolkit": {
"version": "2.11.2", "version": "2.11.2",
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.11.2.tgz", "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.11.2.tgz",

View File

@@ -18,6 +18,7 @@
"@mui/material": "^9.0.0", "@mui/material": "^9.0.0",
"@mui/x-charts": "^9.0.1", "@mui/x-charts": "^9.0.1",
"@mui/x-data-grid": "^9.0.1", "@mui/x-data-grid": "^9.0.1",
"@redux-devtools/extension": "^4.0.0",
"@reduxjs/toolkit": "^2.11.2", "@reduxjs/toolkit": "^2.11.2",
"react": "^19.2.4", "react": "^19.2.4",
"react-dom": "^19.2.4", "react-dom": "^19.2.4",

View File

@@ -1,10 +1,12 @@
import { configureStore } from '@reduxjs/toolkit'; import { configureStore } from '@reduxjs/toolkit';
import listsReducer from './testing/features/quizSlice'; import listsReducer from './testing/features/quizSlice';
const store = configureStore({ const store = configureStore({
reducer: { reducer: {
lists: listsReducer, lists: listsReducer,
}, },
devTools: { trace: true ,traceLimit: 25},
}); });
export type RootState = ReturnType<typeof store.getState>; export type RootState = ReturnType<typeof store.getState>;

View File

@@ -6,9 +6,10 @@ import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
interface SortableItemProps { interface SortableItemProps {
item: string; item: string;
id: string;// чтобы тайпскрипт компилятор не жаловался, добавил в инетрфейс, хотя и так компилируется нормально id: string;// чтобы тайпскрипт компилятор не жаловался, добавил в инетрфейс, хотя и так компилируется нормально
isDisabled:boolean;
} }
export function SortableItem({ item }: SortableItemProps) { export function SortableItem({ item ,isDisabled}: SortableItemProps) {
const id = item; /* идентификатор для useSortable */ const id = item; /* идентификатор для useSortable */
const { const {
attributes, attributes,
@@ -24,7 +25,7 @@ export function SortableItem({ item }: SortableItemProps) {
}; };
return ( return (
<ListItem ref={ setNodeRef } style={ style } { ...attributes } { ...listeners }> <ListItem ref={ isDisabled ? undefined : setNodeRef } style={ style } { ...attributes } { ...listeners }>
<ListItemButton <ListItemButton
sx={{ sx={{
border: '1px solid gray', border: '1px solid gray',

View File

@@ -3,7 +3,7 @@ import type {tTasks} from "../quizData"
import SortableList from '../features/SortableList'; import SortableList from '../features/SortableList';
import { useEffect } from 'react'; import { useEffect } from 'react';
import { useDispatch } from 'react-redux'; import { useDispatch } from 'react-redux';
import { addList } from './quizSlice'; import { addList,mixUp } from './quizSlice';
interface ComponentProps { interface ComponentProps {
tasks: tTasks; tasks: tTasks;
index: number; index: number;
@@ -17,6 +17,11 @@ function Matching({tasks,index}: ComponentProps) {
dispatch(addList({ index, items: answers })); dispatch(addList({ index, items: answers }));
}, []); }, []);
useEffect(() => {
dispatch(mixUp());
}, []);
const answers: string[] = tasks.map((item) => item.answer); const answers: string[] = tasks.map((item) => item.answer);
return ( return (
<Grid container spacing={2}> <Grid container spacing={2}>

View File

@@ -1,8 +1,52 @@
import { Box, Button, Container, Typography } from '@mui/material'; import { Box, Button, Container, Typography } from '@mui/material';
import { quiz } from "../quizData"; import { quiz } from "../quizData";
import { useSelector } from 'react-redux';
import {useState } from 'react';
import Matching from './Matching'; import Matching from './Matching';
import type { RootState } from '../../store';
import store from '../../store';
import { useDispatch } from 'react-redux';
import { mixUp, startTesting, stopTesting } from './quizSlice';
function QuizStats() {
const checkTask = (index: number): string => {
useSelector((state: RootState) => state.lists.lists[index]);
let state = store.getState();
if (state.lists.correctAnswers.length <= index) {
return "";
}
let correctCounter = state.lists.lists[index].reduce((prev, answ, i) => prev + Number(state.lists.correctAnswers[index][i] === answ), 0)
if (correctCounter == state.lists.lists[index].length) {
return "все ответы верные"
}
return `верно ${correctCounter}/${state.lists.lists[index].length}`
}
return (
<Container sx={{ margin: "auto" }}>
<h3>Результаты теста</h3>
<Typography>Задание 1: {checkTask(0)}</Typography>
<Typography>Задание 2: {checkTask(1)}</Typography>
</Container>
)
}
function Quiz() { function Quiz() {
const dispatch = useDispatch();
const [displayingResults, setDisplayingResults] = useState(false);
const resetQuiz = () => {
setDisplayingResults(false);
dispatch(mixUp());
dispatch(startTesting());
}
const checkQuiz = () => {
setDisplayingResults(true);
dispatch(stopTesting());
}
return ( return (
<Container maxWidth="md"> <Container maxWidth="md">
@@ -14,10 +58,13 @@ function Quiz() {
<Matching index={index} tasks={item.tasks} /> <Matching index={index} tasks={item.tasks} />
</Box> </Box>
))} ))}
<Box sx={{ display: 'flex', justifyContent: 'space-around' }}> <Box sx={{ display: 'flex', justifyContent: 'space-around' }}>
<Button variant="contained">Проверить</Button> <Button onClick={checkQuiz} variant="contained">Проверить</Button>
<Button variant="contained">Начать снова</Button> <Button onClick={resetQuiz} variant="contained">Начать снова</Button>
</Box> </Box>
{displayingResults && <QuizStats />}
</Container> </Container>
); );
} }

View File

@@ -15,6 +15,7 @@ function SortableList({ index}: ComponentProps) {
const dispatch = useDispatch(); const dispatch = useDispatch();
const arr = useSelector((state: RootState) => state.lists.lists[index]) const arr = useSelector((state: RootState) => state.lists.lists[index])
const isDisabled = useSelector((state: RootState) => state.lists.isTestingDone)
const draggedItems = arr || []; const draggedItems = arr || [];
const handleDragEnd = (event: any) => { const handleDragEnd = (event: any) => {
@@ -33,7 +34,7 @@ function SortableList({ index}: ComponentProps) {
strategy={verticalListSortingStrategy}> strategy={verticalListSortingStrategy}>
<List> <List>
{draggedItems.map((item) => ( {draggedItems.map((item) => (
<SortableItem key={item} item={item} id={item} /> <SortableItem key={item} item={item} id={item} isDisabled={isDisabled}/>
))} ))}
</List> </List>
</SortableContext> </SortableContext>

View File

@@ -1,11 +1,33 @@
import { createSlice } from '@reduxjs/toolkit'; import { createSlice } from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit'; import type {PayloadAction} from '@reduxjs/toolkit';
function shuffle<T>(array:Array<T>):Array<T> {
let currentIndex = array.length;
// While there remain elements to shuffle...
while (currentIndex != 0) {
// Pick a remaining element...
let randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
interface ListsState { interface ListsState {
lists: string[][]; // хранит перемещаемые элементы каждого списка ответов lists: string[][]; // хранит перемещаемые элементы каждого списка ответов
correctAnswers:string[][];
isTestingDone:boolean
} }
const initialState: ListsState = { const initialState: ListsState = {
lists: [], lists: [],
correctAnswers:[],
isTestingDone:false
}; };
const listsSlice = createSlice({ const listsSlice = createSlice({
@@ -14,7 +36,9 @@ const listsSlice = createSlice({
reducers: { reducers: {
addList: (state, action: PayloadAction<{index: number; items: string[]}>)=>{ addList: (state, action: PayloadAction<{index: number; items: string[]}>)=>{
const { index, items } = action.payload; const { index, items } = action.payload;
state.lists.splice(index, 0, items); state.lists.splice(index, 1, items);
state.correctAnswers.splice(index, 1, items);
}, },
setDraggedItems: (state, action: PayloadAction<{ index: number; items: string[] }>) => { setDraggedItems: (state, action: PayloadAction<{ index: number; items: string[] }>) => {
const { index, items } = action.payload; const { index, items } = action.payload;
@@ -22,9 +46,22 @@ const listsSlice = createSlice({
state.lists[index] = items; // обновляем конкретный список state.lists[index] = items; // обновляем конкретный список
} }
}, },
mixUp: (state) => {
state.lists=state.lists.map((list)=>
{
return shuffle(list);
})
},
stopTesting:(state)=>{
state.isTestingDone=true;
},
startTesting:(state)=>{
state.isTestingDone=false;
}
}, },
}); });
// Экспортируем действия и редьюсер // Экспортируем действия и редьюсер
export const { addList, setDraggedItems } = listsSlice.actions; export const { addList, setDraggedItems,mixUp,startTesting,stopTesting } = listsSlice.actions;
export type {ListsState}
export default listsSlice.reducer; export default listsSlice.reducer;