-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
74 lines (70 loc) · 2.07 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
let diamondIndex;
let attempts = 5;
let gameOver = false;
const win = document.getElementById('ifwin');
function initializeGame(){
attempts = 5;
gameOver = false;
diamondIndex = Math.floor(Math.random() * 20);
if(win.classList.contains("block")){
win.classList.remove("block");
}
const grid = document.getElementById('grid');
grid.innerHTML = '';
for (let i = 0; i < 20; i++) {
const tile = document.createElement('div');
tile.className = 'tile';
tile.dataset.index = i;
tile.addEventListener('click', handleClick);
grid.appendChild(tile);
}
updateResult();
}
function handleClick(event) {
if (gameOver) return;
const clickedIndex = parseInt(event.target.dataset.index);
const tile = event.target;
if (tile.classList.contains('clicked')) return;
if (clickedIndex === diamondIndex){
tile.classList.add('green');
tile.classList.add('diamond');
displayResult('Congratulations! You found the diamond!');
win.className="block";
gameOver = true;
} else {
tile.classList.add('clicked');
attempts--;
updateResult();
if (attempts === 0) {
revealDiamondTile()
displayResult('Game over! You ran out of attempts.');
gameOver = true;
} else if (attempts === 3) {
const row = Math.floor(diamondIndex / 5);
const tiles = document.querySelectorAll('.tile');
tiles.forEach((tile, index) => {
if (Math.floor(index / 5) === row) {
tile.classList.add('highlight');
}
});
}
}
}
function updateResult() {
const result = document.getElementById('result');
result.textContent = `Attempts left: ${attempts}`;
}
function displayResult(message) {
const result = document.getElementById('result');
result.textContent = message;
}
function revealDiamondTile() {
const tiles = document.querySelectorAll('.tile');
tiles.forEach((tile, index) => {
if (index === diamondIndex) {
tile.classList.add('diamond');
tile.classList.add('red');
}
});
}
window.onload = initializeGame;