Created
May 25, 2023 23:59
-
-
Save naoyashiga/0e48e98d05951b199d4c0467c248798f to your computer and use it in GitHub Desktop.
Color Codes Game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useState, useEffect} from "react"; | |
export const ColorCodes = () => { | |
const [colors, setColors] = useState([]); | |
const [correctColor, setCorrectColor] = useState(""); | |
const [isCorrect, setIsCorrect] = useState(false); | |
const [isShowResult, setIsShowResult] = useState(false); | |
const generateRandomHexColors = () => { | |
return [...Array(3)].map(() => { | |
let color = "#" | |
for(let i = 0; i < 6;i++) { | |
color += Math.floor(Math.random() * 16).toString(16) | |
} | |
return color | |
}) | |
} | |
const handleClick = (color) => { | |
setIsShowResult(true) | |
setIsCorrect(color === correctColor) | |
} | |
const handlePlayAgain = () => { | |
setIsShowResult(false) | |
refleshColor() | |
} | |
const refleshColor = () => { | |
const colors = generateRandomHexColors() | |
setColors(colors) | |
setCorrectColor(colors[Math.floor(Math.random() * colors.length -1)]) | |
} | |
useEffect(() => { | |
refleshColor() | |
}, []) | |
return ( | |
<div | |
style={{ | |
display: "flex", | |
flexDirection: "column", | |
alignItems: "center", | |
}} | |
> | |
<h1>Color Codes</h1> | |
<h2>{correctColor}</h2> | |
<h2>What color is this?</h2> | |
<div data-testid="color-container" | |
style={{ | |
display: "flex", | |
flexDirection: "row", | |
alignItems: "center", | |
}} | |
> | |
{ | |
colors.map((color, index) => { | |
const isCorrect = color === correctColor | |
const boxColorStyle = { | |
background: color, | |
width: "100px", | |
height: "100px", | |
cursor:'pointer', | |
border: isCorrect ? '1px solid' :"none" | |
} | |
return isCorrect ? | |
<div key={index} data-testid="correct-color" | |
style={boxColorStyle} onClick={() => handleClick(color)}></div> : <div key={index} data-testid="incorrect-color" style={boxColorStyle} onClick={() => handleClick(color)} ></div> | |
}) | |
} | |
</div> | |
{isShowResult && <> | |
<p>{isCorrect ? 'Correct!' : 'Incorrect!'}</p> | |
<button onClick={() => handlePlayAgain()}>Play Again</button> | |
</> | |
} | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Color Codes Game | Frontend Interview Coding Problem