📜  涉及正方形或矩形区域的单词问题在线测验(1)

📅  最后修改于: 2023-12-03 15:40:45.729000             🧑  作者: Mango

涉及正方形或矩形区域的单词问题在线测验

这是一个在线测验程序,旨在帮助用户提高识别和理解涉及正方形或矩形区域的单词的能力。该程序要求用户阅读给定的句子,并在句子中标出涉及正方形或矩形区域的单词。

功能与特点
  • 给定一组句子,存在涉及正方形或矩形区域的单词。
  • 通过标记这些单词,帮助用户提高对这些术语的识别和理解。
  • 在进行测试时显示每个问题的计时器,以测试用户的速度和准确性。
  • 提供反馈,显示用户选择的标记是否正确。
  • 显示最终的分数和答案,以便用户可以评估自己的选择。
技术实现
  • 前端使用ReactJS和Bootstrap库创建。
  • 后端使用NodeJS和ExpressJS框架创建。
  • 数据存储在MongoDB数据库中。
  • 涉及单词的句子和正确答案存储在数据库中,并动态加载到前端进行测试。
代码片段

示例前端代码片段:

import React, { useState, useEffect } from 'react';

const Test = () => {
  const [sentences, setSentences] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [timer, setTimer] = useState(0);
  const [selectedWords, setSelectedWords] = useState([]);

  // Load sentences from backend on component mount
  useEffect(() => {
    fetch('/api/sentences')
      .then(res => res.json())
      .then(data => setSentences(data))
      .catch(err => console.error(err));
  }, []);

  // Timer logic for each sentence
  useEffect(() => {
    let intervalId;
    if (currentIndex < sentences.length) {
      intervalId = setInterval(() => {
        setTimer(prevTimer => prevTimer + 1);
      }, 1000);
    }
    return () => clearInterval(intervalId);
  }, [currentIndex, sentences]);

  // Functions to select and deselect a word
  const handleWordSelect = (index) => {
    const word = selectedWords[currentIndex][index];
    const newSelectedWords = [...selectedWords];
    if (newSelectedWords[currentIndex].indexOf(word) === -1) {
      newSelectedWords[currentIndex] = [...newSelectedWords[currentIndex], word];
    } else {
      newSelectedWords[currentIndex].splice(newSelectedWords[currentIndex].indexOf(word), 1);
    }
    setSelectedWords(newSelectedWords);
  }

  // Function to check user's answer for each sentence
  const checkAnswer = () => {
    const correctAnswer = sentences[currentIndex].words;
    const userAnswer = selectedWords[currentIndex];
    let isCorrect = false;
    if (correctAnswer.length === userAnswer.length) {
      isCorrect = correctAnswer.every(word => userAnswer.includes(word));
    }
    return isCorrect;
  }

  // Function to move to the next sentence
  const handleNextSentence = () => {
    const isAnswerCorrect = checkAnswer();
    // Update score
    if (isAnswerCorrect) {
      setScore(prevScore => prevScore + 1);
    }
    // Move to next sentence or to results page
    if (currentIndex === sentences.length - 1) {
      setTestCompleted(true);
    } else {
      setCurrentIndex(prevIndex => prevIndex + 1);
      setTimer(0);
      setSelectedWords(prevSelectedWords => 
        [...prevSelectedWords, []]
      );
    }
  }

  return (
    <div className="container">
      {currentIndex < sentences.length &&
        <div className="card">
          <div className="card-body">
            <div className="card-text">
              <div className="mb-3">
                <h5 className="d-inline-block mr-3">{currentIndex + 1}.</h5>
                <p className="d-inline-block">{sentences[currentIndex].text}</p>
              </div>
              <div>
                {sentences[currentIndex].words.map((word, index) => (
                  <button
                    key={index}
                    type="button"
                    className={`btn btn-sm mx-1 mb-1 ${selectedWords[currentIndex].includes(word) ? 'btn-dark' : 'btn-outline-secondary'}`}
                    onClick={() => handleWordSelect(index)}
                  >
                    {word}
                  </button>
                ))}
              </div>
            </div>
            <div className="card-footer text-right">
              <button className="btn btn-primary" onClick={handleNextSentence}>Next</button>
              <span className="badge badge-secondary ml-3">{timer}s</span>
            </div>
          </div>
        </div>
      }
      ...
    </div>
  );
};

示例后端代码片段:

const express = require('express');
const router = express.Router();

// MongoDB models
const Sentence = require('../models/sentence');

// REST API routes
router.get('/sentences', (req, res) => {
  Sentence.find({})
    .select('-words')
    .then(sentences => res.json(sentences))
    .catch(err => console.error(err));
});

router.get('/sentences/:id', (req, res) => {
  Sentence.findById(req.params.id)
    .then(sentence => res.json(sentence))
    .catch(err => console.error(err));
});

router.post('/sentences/:id', (req, res) => {
  Sentence.findById(req.params.id)
    .then(sentence => {
      sentence.words = req.body.words;
      sentence.save()
        .then(() => res.json({ success: true }))
        .catch(err => console.error(err));
    })
    .catch(err => console.error(err));
});

...

module.exports = router;
如何运行
  • 下载并安装Node.js和MongoDB。
  • 克隆此程序的代码库到本地。
  • 在命令行中运行npm install,以安装所有包和依赖项。
  • 在命令行中启动MongoDB服务。
  • 在命令行中运行npm start,以启动程序。
  • 在浏览器中打开http://localhost:5000,以访问应用程序。
作者
  • 作者:Jun Yao
  • GitHub:junnyal
版权和许可

本程序遵循MIT许可证。