-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
175 lines (159 loc) · 6.17 KB
/
script.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
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
document.addEventListener('DOMContentLoaded', () => {
const grid = document.querySelector('.grid');
const size = 4;
let board = [];
let currentScore = 0;
const currentScoreElem = document.getElementById('current-score');
// Get the high score from local storage or set it to 0 if not found
let highScore = localStorage.getItem('2048-highScore') || 0;
const highScoreElem = document.getElementById('high-score');
highScoreElem.textContent = highScore;
const gameOverElem = document.getElementById('game-over');
// Function to update the score
function updateScore(value) {
currentScore += value;
currentScoreElem.textContent = currentScore;
if (currentScore > highScore) {
highScore = currentScore;
highScoreElem.textContent = highScore;
localStorage.setItem('2048-highScore', highScore);
}
}
// Function to restart the game
function restartGame() {
currentScore = 0;
currentScoreElem.textContent = '0';
gameOverElem.style.display = 'none';
initializeGame();
}
// Function to initialize the game
function initializeGame() {
board = [...Array(size)].map(e => Array(size).fill(0));
placeRandom();
placeRandom();
renderBoard();
}
// Function to render the game board on the UI
function renderBoard() {
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
const cell = document.querySelector(`[data-row="${i}"][data-col="${j}"]`);
const prevValue = cell.dataset.value;
const currentValue = board[i][j];
if (currentValue !== 0) {
cell.dataset.value = currentValue;
cell.textContent = currentValue;
// Animation handling
if (currentValue !== parseInt(prevValue) && !cell.classList.contains('new-tile')) {
cell.classList.add('merged-tile');
}
} else {
cell.textContent = '';
delete cell.dataset.value;
cell.classList.remove('merged-tile', 'new-tile');
}
}
}
// Cleanup animation classes
setTimeout(() => {
const cells = document.querySelectorAll('.grid-cell');
cells.forEach(cell => {
cell.classList.remove('merged-tile', 'new-tile');
});
}, 300);
}
// Function to place a random tile on the board
function placeRandom() {
const available = [];
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
if (board[i][j] === 0) {
available.push({ x: i, y: j });
}
}
}
if (available.length > 0) {
const randomCell = available[Math.floor(Math.random() * available.length)];
board[randomCell.x][randomCell.y] = Math.random() < 0.9 ? 2 : 4;
const cell = document.querySelector(`[data-row="${randomCell.x}"][data-col="${randomCell.y}"]`);
cell.classList.add('new-tile'); // Animation for new tiles
}
}
// Function to move the tiles based on arrow key input
function move(direction) {
let hasChanged = false;
if (direction === 'ArrowUp' || direction === 'ArrowDown') {
for (let j = 0; j < size; j++) {
const column = [...Array(size)].map((_, i) => board[i][j]);
const newColumn = transform(column, direction === 'ArrowUp');
for (let i = 0; i < size; i++) {
if (board[i][j] !== newColumn[i]) {
hasChanged = true;
board[i][j] = newColumn[i];
}
}
}
} else if (direction === 'ArrowLeft' || direction === 'ArrowRight') {
for (let i = 0; i < size; i++) {
const row = board[i];
const newRow = transform(row, direction === 'ArrowLeft');
if (row.join(',') !== newRow.join(',')) {
hasChanged = true;
board[i] = newRow;
}
}
}
if (hasChanged) {
placeRandom();
renderBoard();
checkGameOver();
}
}
// Function to transform a line (row or column) based on move direction
function transform(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]); // Update score when tiles merged
newLine.splice(i + 1, 1);
}
}
while (newLine.length < size) {
newLine.push(0);
}
if (!moveTowardsStart) {
newLine.reverse();
}
return newLine;
}
// Function to check if the game is over
function checkGameOver() {
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
if (board[i][j] === 0) {
return; // There is an empty cell, so game not over
}
if (j < size - 1 && board[i][j] === board[i][j + 1]) {
return; // There are horizontally adjacent equal cells, so a move is possible
}
if (i < size - 1 && board[i][j] === board[i + 1][j]) {
return; // There are vertically adjacent equal cells, so a move is possible
}
}
}
// If we reach here, no moves are possible
gameOverElem.style.display = 'flex';
}
// Event listeners
document.addEventListener('keydown', event => {
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(event.key)) {
move(event.key);
}
});
document.getElementById('restart-btn').addEventListener('click', restartGame);
initializeGame();
});