드래그 앤 드롭 기능 추가
목표: 퍼즐 조각을 드래그 앤 드롭하는 로직을 구현합니다.
- 드래그 시작, 드래그 오버 및 드롭 이벤트에 대한 핸들러를 추가합니다.
- 드롭 시 퍼즐 조각을 교환하는 로직을 구현합니다.
// src/components/PuzzleGame.js
const PuzzleGame = () => {
// ...이전 코드
// 드래그 이벤트 시작 처리
const handleDragStart = (e, position) => {
e.dataTransfer.setData("text/plain", position);
};
// 드롭 이벤트 처리
const handleDrop = (e, position) => {
e.preventDefault();
const originalPosition = e.dataTransfer.getData("text");
// 여기에 퍼즐 조각의 위치를 교환하는 로직을 추가합니다.
setPositions((prevPositions) => {
const newPos = [...prevPositions];
[newPos[originalPosition], newPos[position]] = [
newPos[position],
newPos[originalPosition]
];
return newPos;
});
};
// 기본 동작을 방지하여 드롭 동작 허용
const handleDragOver = (e) => {
e.preventDefault();
};
// 추가된 드래그 앤 드롭 핸들러로 퍼즐 조각 렌더링
};
// src/components/PuzzleGame.js
const PuzzleGame = () => {
// ...이전 코드
return (
<div className="game-container">
<div className="reference-image">
<img src={imgUrl} alt="Reference Image" />
</div>
<div className="puzzle-container">
{positions.map((pos, index) => {
const x = (pos % 4) * 100;
const y = Math.floor(pos / 4) * 100;
return (
<div
key={index}
className="puzzle-piece"
draggable
onDragStart={(e) => handleDragStart(e, index)}
onDrop={(e) => handleDrop(e, index)}
onDragOver={handleDragOver}
style={{
backgroundImage: `url('${imgUrl}')`,
backgroundPosition: `-${x}px -${y}px`
}}
/>
);
})}
</div>
</div>
);
};