-게임 시작
-테이블을 그려준다
-랜덤하게 지뢰를 심는다
-클릭하여 찾는다
-우클릭 으로 깃발을 세운다
-빈 공간이 없으면 게임을 끝낸다
function drawTable() {
data = plantMine();
data.forEach((row) => {
const $tr = document.createElement('tr');
row.forEach((cell) => {
const $td = document.createElement('td');
$tr.append($td);
});
$tbody.append($tr);
$tbody.addEventListener('contextmenu', onRightClick);
$tbody.addEventListener('click', onLeftClick);
});
}
drawTable();
const CODE = {
NORMAL: -1, // 닫힌 칸(지뢰 없음)
QUESTION: -2,
FLAG: -3,
QUESTION_MINE: -4,
FLAG_MINE: -5,
MINE: -6,
OPENED: 0, // 0 이상이면 다모두 열린 칸
};
let row = 5;
let cell=5;
let mine=3;
let data;
function plantMine() {
const candidate = Array(row * cell).fill().map((arr, i) => {
return i;
});
const shuffle = [];
while (candidate.length > row * cell - mine) {
const chosen = candidate.splice(Math.floor(Math.random() * candidate.length), 1)[0];
shuffle.push(chosen);
console.log(shuffle);
}
const data = [];
for (let i = 0; i < row; i++) {
const rowData = [];
data.push(rowData);
for (let j = 0; j < cell; j++) {
rowData.push(CODE.NORMAL);
}
}
for (let k = 0; k < shuffle.length; k++) {
const ver = Math.floor(shuffle[k] / cell); // 7번째 줄
const hor = shuffle[k] % cell; // 1번째 칸
data[ver][hor] = CODE.MINE;
}
return data;
}
function onLeftClick(event) {
const target = event.target;
const rowIndex = target.parentNode.rowIndex;
const cellIndex = target.cellIndex;
const cellData = data[rowIndex][cellIndex];
if (cellData === CODE.NORMAL) {
openAround(rowIndex, cellIndex);
} else if (cellData === CODE.MINE) {
target.textContent = '펑';
target.className = 'opened';
clearInterval(interval);
$tbody.removeEventListener('contextmenu', onRightClick);
$tbody.removeEventListener('click', onLeftClick);
}
}
function onRightClick(event) {
event.preventDefault();
const target = event.target;
const rowIndex = target.parentNode.rowIndex;
const cellIndex = target.cellIndex;
const cellData = data[rowIndex][cellIndex];
if (cellData === CODE.MINE) {
data[rowIndex][cellIndex] = CODE.QUESTION_MINE;
target.className = 'question';
target.textContent = '?';
} else if (cellData === CODE.QUESTION_MINE) {
data[rowIndex][cellIndex] = CODE.FLAG_MINE;
target.className = 'flag';
target.textContent = '!';
} else if (cellData === CODE.FLAG_MINE) {
data[rowIndex][cellIndex] = CODE.MINE;
target.className = '';
target.textContent = '';
} else if (cellData === CODE.NORMAL) {
data[rowIndex][cellIndex] = CODE.QUESTION;
target.className = 'question';
target.textContent = '?';
} else if (cellData === CODE.QUESTION) {
data[rowIndex][cellIndex] = CODE.FLAG;
target.className = 'flag';
target.textContent = '!';
} else if (cellData === CODE.FLAG) {
data[rowIndex][cellIndex] = CODE.NORMAL;
target.className = '';
target.textContent = '';
}
}
if (openCount === row * cell - mine) {
clearInterval(interval);
$tbody.removeEventListener('contextmenu', onRightClick);
$tbody.removeEventListener('click', onLeftClick);
setTimeout(() => {
alert(`종료`);
}, 500);
}