Search

숫자슬라이드 게임[1단계]

대분류
STEP06 이벤트응용
소분류
이벤트응용

영상

개념

<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #target { margin: 0 auto; display: table; } td { width: 100px; height: 100px; border: 3px solid white; border-radius: 10px; text-align: center; color: white; font-size: 30px; font-weight: bold; cursor: pointer; } </style> </head> <body onload="init()"> <div id="target"> </div> <script> let $target = document.querySelector("#target"); let size = 5; let $table = document.createElement("table"); let $tdList = []; let $hintTdList = []; // 0주변의 td태그값 let answer = [0, 0]; // 값이 0인 y좌표,x좌표 function init() { for(let i=0; i<size; i++) { let $tr = document.createElement("tr"); let $temp = []; for(let j=0; j<size; j++) { let $td = document.createElement("td"); $td.style.backgroundColor = "coral"; $td.addEventListener("click", clickEvent); $tr.append($td); $temp.push($td); } $tdList.push($temp); $table.append($tr); } $target.append($table); setNumber(); } function setNumber() { let numList = []; for(let i=0; i<size*size; i++) { numList.push(i); } // numList 일차원 배열을 shuffle for(let i=0; i<100; i++) { let index = Math.floor(Math.random() * numList.length); let temp = numList[0]; numList[0] = numList[index]; numList[index] = temp; } let index = 0; for(let i=0; i<size; i++) { for(let j=0; j<size; j++) { $tdList[i][j].innerText = numList[index]; if($tdList[i][j].innerText == 0) { $tdList[i][j].style.backgroundColor = ""; } index += 1; } } } function clickEvent() { // 선택한 위치의 좌표를 구하기 let y = 0; let x = 0; for(let i=0; i<size; i++) { for(let j=0; j<size; j++) { if(this == $tdList[i][j]) { y = i; x = j; break; } } } console.log("선택한 위치의 좌표 >>> y = " + y + ", x = " + x); hint(); // 현재 클릭한 좌표 = y(2), x(2) // $hintTdList = [19, 4, 1, 7] let check = false; for(let i=0; i<$hintTdList.length; i++) { if($tdList[y][x] == $hintTdList[i]) { check = true; break; } } console.log(check); if(check) { let temp = $tdList[y][x].innerText; // 1 $tdList[y][x].innerText = 0; // 내가 선택한 위치의 값 = 0 $tdList[answer[0]][answer[1]].innerText = temp; // $tdList[y][x].style.backgroundColor = ""; $tdList[answer[0]][answer[1]].style.backgroundColor = "coral"; } } function hint() { $hintTdList = []; for(let i=0; i<size; i++) { for(let j=0; j<size; j++) { if($tdList[i][j].innerText == 0) { answer[0] = i; answer[1] = j; // 상 if(0 <= i - 1 && i - 1 < size) { $hintTdList.push($tdList[i - 1][j]); } // 하 if(0 <= i + 1 && i + 1 < size) { $hintTdList.push($tdList[i + 1][j]); } // 좌 if(0 <= j + 1 && j + 1 < size) { $hintTdList.push($tdList[i][j + 1]); } // 우 if(0 <= j - 1 && j - 1 < size) { $hintTdList.push($tdList[i][j - 1]); } break; } } } let str = ""; for(let i=0; i<$hintTdList.length; i++) { str += $hintTdList[i].innerText + " "; } console.log(str); } </script> </body> </html>
Java
복사