본문 바로가기

자바스크립트

간단한 퍼즐 게임: 퍼즐 조각을 이동하여 이미지를 완성하는 퍼즐 게임을 만듭니다.

반응형

간단한 퍼즐 게임은 퍼즐 조각을 이동하여 이미지를 완성하는 게임입니다.

개념설명:
퍼즐 게임은 주어진 이미지를 여러 조각으로 나누고, 플레이어는 이 조각들을 이동하여 원본 이미지를 완성하는 게임입니다.


예제 코드:

 

<!DOCTYPE html>
<html>
<head>
    <title>간단한 퍼즐 게임</title>
    <style>
        .puzzle-container {
            width: 300px;
            height: 300px;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-gap: 5px;
        }

        .puzzle-piece {
            width: 100px;
            height: 100px;
            background-size: 300px 300px;
            cursor: pointer;
            transition: background 0.3s ease-in-out;
            user-drag: none;
        }

        .puzzle-piece:hover {
            background: url('original-image.jpg') no-repeat;
        }
    </style>
</head>
<body>
    <div class="puzzle-container">
        <div class="puzzle-piece" style="background: url('piece1.jpg') no-repeat;"></div>
        <div class="puzzle-piece" style="background: url('piece2.jpg') no-repeat;"></div>
        <div class="puzzle-piece" style="background: url('piece3.jpg') no-repeat;"></div>
        <!-- 추가 퍼즐 조각들 -->
    </div>

    <script>
        let selectedPiece = null;

        document.querySelectorAll('.puzzle-piece').forEach(piece => {
            piece.addEventListener('mousedown', (e) => {
                selectedPiece = piece;
                piece.style.zIndex = '1';
                piece.style.cursor = 'grabbing';
                piece.style.position = 'absolute'; // 추가: 조각을 절대 위치로 변경
            });

            piece.addEventListener('mouseup', () => {
                selectedPiece = null;
                piece.style.zIndex = '0';
                piece.style.cursor = 'pointer';
            });
        });

        document.addEventListener('mousemove', (e) => {
            if (!selectedPiece) return;
            
            selectedPiece.style.left = e.pageX - selectedPiece.clientWidth / 2 + 'px';
            selectedPiece.style.top = e.pageY - selectedPiece.clientHeight / 2 + 'px';
        });
    </script>
</body>
</html>

 

 

전문용어 상세하게 설명:
퍼즐 게임: 이미지를 조각으로 나누어 이동시켜 원본 이미지를 재구성하는 게임.
퍼즐 조각: 원본 이미지를 나눈 작은 이미지 조각.
이동: 퍼즐 조각을 클릭하거나 드래그하여 다른 위치로 이동시키는 동작.

반응형