소프트웨어 이론교육/웹 프로그래밍 기본

Javascript를 이용한 퍼즐(같은그림찾기) 구현

마루설아 2022. 7. 27. 15:30
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>짝 맞추기 퍼즐 구현</title>
    <style>
        div#puzzle{
            border: 3px solid black;
            width: 400px;
            height: 400px;
            padding: 0;
        }

        #puzzle .cell{
            width: 100px;
            height: 100px;
            border: 1px solid red;
            box-sizing: border-box;
            float: left;
            margin: 0;
            text-align: center;
            line-height: 100px;
            background-color: orange;
            font-size: 40px;
            font-weight: bold;
        }

        #test{
            position:absolute;
            top: 500px;
            width: 100px;
            height: 100px;
        }
    </style>
    <script>
        class PuzzleGame{
            constructor(){
                this.cells = [];
                this.select = [];
                this.selectBox = [];
                this.count = 0;

                this.init(); 
            }

            // javascript를 이용해 body에 HTML 삽입
            init(){
                const body = document.body;
                body.innerHTML = `<h1>Puzzle</h1> <hr />`
                
                const puzzle = document.createElement("div");
                puzzle.id = "puzzle";
                body.appendChild(puzzle);

                for(var i=0; i<16; i++){
                    var cell = document.createElement("div");
                    cell.className = "cell";
                    

                    puzzle.appendChild(cell);
                    this.cells.push(cell);
                }

                this.cells.forEach(function(item, i){
                    let charCode = i % 8 + 65
                    item.innerText = String.fromCharCode(charCode);
                });
            }

            swap(i, j){
                let tmp = this.cells[i].innerText;
                this.cells[i].innerText = this.cells[j].innerText;
                this.cells[j].innerText = tmp;
            }

            start(){
                for(let i=0; i<50; i++){
                    let idx1 = Math.abs(Math.floor(Math.random()*16));
                    let idx2 = Math.abs(Math.floor(Math.random()*16));
                    this.swap(idx1, idx2);
                }

                setTimeout(()=>{
                    // 모든 요소 숨기기
                    this.cells.forEach((item, i)=>{
                        item['ch'] = item.innerText;
                        item.innerHTML ="";

                        item.addEventListener('click', (e)=>{
                            item.innerText = e.currentTarget.ch;
                            this.compare(e.currentTarget);
                        });
                    });
                }, 3000);
            }

            compare(cell){
                // 첫번째 클릭 cell.ch, 두번째 클릭 cell.ch 비교
                // 같으면 남기고 다르면 숨긴다

                if(cell.style.backgroundColor == "aqua" || cell.style.backgroundColor == "green"){
                    return;
                }

                cell.removeEventListener('click', this.compare);
                this.select.push(cell.innerText);
                this.selectBox.push(cell);
                cell.style.backgroundColor = "green";
                this.count++;

                if(this.count == 2){
                    this.count = 0;
                    let first = this.select.pop();
                    let second = this.select.pop();
                    let firstBox = this.selectBox.pop();
                    let secondBox = this.selectBox.pop();

                    if(first == second){
                        setTimeout(()=>{
                            console.log("good");
                            firstBox.style.backgroundColor = "aqua"
                            secondBox.style.backgroundColor = "aqua"
                            firstBox.removeEventListener('click', this.compare);
                            secondBox.removeEventListener('click', this.compare);
                        }, 200);
                    } 

                    else{
                        setTimeout(()=>{
                            console.log("bad");
                            firstBox.innerText = "";
                            firstBox.style.backgroundColor = "orange";
                            secondBox.innerText = "";
                            secondBox.style.backgroundColor = "orange";
                        }, 500);
                    }
                }
            }
        }

        function main(){
            new PuzzleGame().start();
        }

        window.addEventListener("load", main);      
    </script>
</head>
<body>
</body>
</html>