-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
224 lines (195 loc) · 7.37 KB
/
script.js
File metadata and controls
224 lines (195 loc) · 7.37 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
document.addEventListener('DOMContentLoaded', () => {
const root = document.documentElement;
const gridContainer = document.getElementById('grid-container');
const scoreElement = document.getElementById('score');
const bestScoreElement = document.getElementById('best-score');
const gameOverElement = document.getElementById('game-over');
const finalScoreElement = document.getElementById('final-score');
const restartButton = document.getElementById('restart-button');
const tryAgainButton = document.getElementById('try-again-button');
const difficultySelect = document.getElementById('difficulty');
// Sound Effects
const moveSound = document.getElementById('move-sound');
const mergeSound = document.getElementById('merge-sound');
const gameOverSound = document.getElementById('game-over-sound');
let size = 4;
let grid = [];
let score = 0;
let bestScore = localStorage.getItem('bestScore') || 0;
bestScoreElement.textContent = bestScore;
// Touch controls
let touchStartX = 0;
let touchStartY = 0;
function setGridSize(newSize) {
size = newSize;
root.style.setProperty('--grid-size', size);
}
function setupGrid() {
setGridSize(parseInt(difficultySelect.value));
grid = Array.from({ length: size }, () => Array(size).fill(0));
score = 0;
updateScore(0);
gameOverElement.style.display = 'none';
addRandomTile();
addRandomTile();
renderBoard();
}
function renderBoard() {
gridContainer.innerHTML = ''; // Clear the entire grid
// First, create the background cells
for (let r = 0; r < size; r++) {
for (let c = 0; c < size; c++) {
const cell = document.createElement('div');
cell.classList.add('grid-cell');
cell.style.setProperty('--x', c + 1);
cell.style.setProperty('--y', r + 1);
gridContainer.appendChild(cell);
}
}
// Then, create the tiles on top
for (let r = 0; r < size; r++) {
for (let c = 0; c < size; c++) {
if (grid[r][c] !== 0) {
const tile = createTile(r, c, grid[r][c]);
gridContainer.appendChild(tile);
}
}
}
}
function createTile(r, c, value, isNew = false) {
const tile = document.createElement('div');
tile.classList.add('tile');
if (isNew) {
tile.classList.add('new');
}
tile.style.setProperty('--x', c + 1);
tile.style.setProperty('--y', r + 1);
tile.dataset.value = value;
tile.textContent = value;
return tile;
}
function addRandomTile() {
let emptyCells = [];
for (let r = 0; r < size; r++) {
for (let c = 0; c < size; c++) {
if (grid[r][c] === 0) {
emptyCells.push({ r, c });
}
}
}
if (emptyCells.length > 0) {
const { r, c } = emptyCells[Math.floor(Math.random() * emptyCells.length)];
const newValue = Math.random() < 0.9 ? 2 : 4;
grid[r][c] = newValue;
// Add the new tile to the grid without a full re-render for the animation
const tile = createTile(r, c, newValue, true);
gridContainer.appendChild(tile);
}
}
function move(direction) {
let moved = false;
let tempGrid = JSON.parse(JSON.stringify(grid));
const moveLogic = (line, moveTowardsStart) => {
let newLine = line.filter(cell => cell !== 0);
if (!moveTowardsStart) newLine.reverse();
for (let i = 0; i < newLine.length - 1; i++) {
if (newLine[i] === newLine[i + 1]) {
newLine[i] *= 2;
updateScore(newLine[i]);
playSound(mergeSound);
newLine.splice(i + 1, 1);
}
}
while (newLine.length < size) newLine.push(0);
if (!moveTowardsStart) newLine.reverse();
return newLine;
};
if (direction === 'ArrowUp' || direction === 'ArrowDown') {
for (let c = 0; c < size; c++) {
let column = grid.map(row => row[c]);
let newColumn = moveLogic(column, direction === 'ArrowUp');
for (let r = 0; r < size; r++) {
grid[r][c] = newColumn[r];
}
}
} else if (direction === 'ArrowLeft' || direction === 'ArrowRight') {
for (let r = 0; r < size; r++) {
grid[r] = moveLogic(grid[r], direction === 'ArrowLeft');
}
}
if (JSON.stringify(tempGrid) !== JSON.stringify(grid)) {
moved = true;
playSound(moveSound);
renderBoard(); // Full re-render to reflect moves
addRandomTile(); // Add a new tile after the move
if (isGameOver()) {
showGameOver();
}
}
}
function updateScore(points) {
score += points;
scoreElement.textContent = score;
if (score > bestScore) {
bestScore = score;
bestScoreElement.textContent = bestScore;
localStorage.setItem('bestScore', bestScore);
}
}
function isGameOver() {
for (let r = 0; r < size; r++) {
for (let c = 0; c < size; c++) {
if (grid[r][c] === 0) return false;
if (r < size - 1 && grid[r][c] === grid[r + 1][c]) return false;
if (c < size - 1 && grid[r][c] === grid[r][c + 1]) return false;
}
}
return true;
}
function showGameOver() {
finalScoreElement.textContent = score;
gameOverElement.style.display = 'flex';
playSound(gameOverSound);
}
function playSound(sound) {
if (sound) {
sound.currentTime = 0;
sound.play().catch(e => console.log('Sound playback failed:', e));
}
}
// Event Listeners
restartButton.addEventListener('click', setupGrid);
tryAgainButton.addEventListener('click', setupGrid);
difficultySelect.addEventListener('change', setupGrid);
document.addEventListener('keydown', (e) => {
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
e.preventDefault();
move(e.key);
}
});
document.addEventListener('touchstart', (e) => {
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
}, { passive: false });
document.addEventListener('touchend', (e) => {
const touchEndX = e.changedTouches[0].clientX;
const touchEndY = e.changedTouches[0].clientY;
handleSwipe(touchEndX, touchEndY);
});
function handleSwipe(endX, endY) {
const diffX = touchStartX - endX;
const diffY = touchStartY - endY;
const threshold = 50;
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > threshold) {
move(diffX > 0 ? 'ArrowLeft' : 'ArrowRight');
}
} else {
if (Math.abs(diffY) > threshold) {
move(diffY > 0 ? 'ArrowUp' : 'ArrowDown');
}
}
}
// Initial setup
setupGrid();
});