|
| 1 | +import { useEffect, useState } from '/runtime/v1/react@18.x'; |
| 2 | + |
| 3 | +const colors = ['red', 'blue', 'green', 'yellow']; |
| 4 | +const words = ['RED', 'BLUE', 'GREEN', 'YELLOW']; |
| 5 | + |
| 6 | +function getRandomElement<T>(arr: T[]): T { |
| 7 | + return arr[Math.floor(Math.random() * arr.length)]!; |
| 8 | +} |
| 9 | + |
| 10 | +type StroopTaskProps = { |
| 11 | + done: (data: { score: number }) => void; |
| 12 | +}; |
| 13 | + |
| 14 | +export const StroopTask: React.FC<StroopTaskProps> = () => { |
| 15 | + const [currentWord, setCurrentWord] = useState(''); |
| 16 | + const [currentColor, setCurrentColor] = useState(''); |
| 17 | + const [score, setScore] = useState(0); |
| 18 | + const [timeLeft, setTimeLeft] = useState(60); // 60 seconds for the task |
| 19 | + |
| 20 | + useEffect(() => { |
| 21 | + const interval = setInterval(() => { |
| 22 | + setTimeLeft((prevTime) => (prevTime > 0 ? prevTime - 1 : 0)); |
| 23 | + }, 1000); |
| 24 | + return () => clearInterval(interval); |
| 25 | + }, []); |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + if (timeLeft > 0) { |
| 29 | + generateNewTask(); |
| 30 | + } |
| 31 | + }, [timeLeft]); |
| 32 | + |
| 33 | + const generateNewTask = () => { |
| 34 | + const word = getRandomElement(words); |
| 35 | + const color = getRandomElement(colors); |
| 36 | + setCurrentWord(word); |
| 37 | + setCurrentColor(color); |
| 38 | + }; |
| 39 | + |
| 40 | + const handleColorClick = (color: string) => { |
| 41 | + if (color === currentColor) { |
| 42 | + setScore(score + 1); |
| 43 | + } |
| 44 | + generateNewTask(); |
| 45 | + }; |
| 46 | + |
| 47 | + return ( |
| 48 | + <div> |
| 49 | + <h1>Stroop Task</h1> |
| 50 | + <div> |
| 51 | + <h2>Time Left: {timeLeft} seconds</h2> |
| 52 | + <h2>Score: {score}</h2> |
| 53 | + </div> |
| 54 | + {timeLeft > 0 ? ( |
| 55 | + <div> |
| 56 | + <h2 style={{ color: currentColor }}>{currentWord}</h2> |
| 57 | + <div> |
| 58 | + {colors.map((color) => ( |
| 59 | + <button |
| 60 | + key={color} |
| 61 | + style={{ backgroundColor: color, color: 'white', margin: '5px', padding: '10px' }} |
| 62 | + onClick={() => handleColorClick(color)} |
| 63 | + > |
| 64 | + {color.toUpperCase()} |
| 65 | + </button> |
| 66 | + ))} |
| 67 | + </div> |
| 68 | + </div> |
| 69 | + ) : ( |
| 70 | + <h2>Time is up! Your final score is {score}</h2> |
| 71 | + )} |
| 72 | + </div> |
| 73 | + ); |
| 74 | +}; |
0 commit comments