Skip to content

Instantly share code, notes, and snippets.

@naoyashiga
Created May 25, 2023 23:59
Show Gist options
  • Save naoyashiga/0e48e98d05951b199d4c0467c248798f to your computer and use it in GitHub Desktop.
Save naoyashiga/0e48e98d05951b199d4c0467c248798f to your computer and use it in GitHub Desktop.
Color Codes Game
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>
);
};
@s2170375
Copy link

s2170375 commented Jul 4, 2024

Screenshot 2024-07-03 at 22 38 00

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment