forked from KilledByAPixel/LittleJS-AI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2048.html
More file actions
427 lines (372 loc) · 13 KB
/
Copy path2048.html
File metadata and controls
427 lines (372 loc) · 13 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
<!DOCTYPE html><head>
<title>LittleJS 2048</title>
<meta charset=utf-8>
</head><body style="background:#000">
<script src="../dist/littlejs.js?1.18.15"></script>
<script src="../templates/soundGenerator.js"></script>
<script>
'use strict';
// engine settings, do not remove
debugWatermark = false;
showEngineVersion = false;
paused = false;
gravity = vec2(0, 0);
cameraPos = vec2(0, 0);
cameraScale = 32;
enablePhysicsSolver = false;
showSplashScreen = false;
fontDefault = 'arial';
///////////////////////////////////////////////////////////////////////////////
// 2048 Game
const GRID = 4;
const CELL_SIZE = 1;
const GAP = .12;
const SLIDE_TIME = .12; // seconds for a tile to slide to its new cell
const SPAWN_TIME = .14; // grow-in time for a newly spawned tile
const MERGE_POP_TIME = .18; // brief pulse on the survivor after a merge
let tiles = []; // every visible tile (including the dying ones during a slide)
let grid; // grid[y][x] = tile reference or null (logical state)
let animT = 0; // remaining slide time; input is locked while > 0
let pendingSpawn = false;
let score = 0;
let best = 0;
let gameOver = false;
let won = false;
let continueAfterWin = false;
let swipeStartScreen;
let swipeArmed = false;
let sMove, sMerge, sSpawn, sLose, sWin;
function gameInit()
{
canvasClearColor = hsl(0, 0, .08);
best = +localStorage.getItem('ljs2048_best') || 0;
sMove = new SoundGenerator({frequency: 260, release: .06, volume: .7, randomness: .02});
sMerge = new SoundGenerator({frequency: 190, pitchJump: 320, pitchJumpTime: .02, release: .14, volume: .9, randomness: .02});
sSpawn = new SoundGenerator({frequency: 520, release: .05, volume: .35, randomness: .05});
sLose = new SoundGenerator({frequency: 120, slide: -.15, release: .35, volume: .9, randomness: .02});
sWin = new SoundGenerator({frequency: 620, pitchJump: 220, pitchJumpTime: .05, release: .25, volume: 1, randomness: .01});
newGame();
}
///////////////////////////////////////////////////////////////////////////////
function makeTile(value, gx, gy)
{
return {
value, // logical value (used for merges)
shownValue: value, // value rendered on the tile (lags behind during a merge slide)
gx, gy, // target grid coords
ax: gx, ay: gy, // current animated grid coords (rendered)
srcX: gx, srcY: gy, // animation start coords for this slide
spawnT: 0, // > 0 while the spawn-pop is playing
mergeT: 0, // > 0 while the merge-pop is playing
pendingMerge: false,// becomes true at move time; resolves at slide end
dying: false, // absorbed tile; removed after the slide
};
}
function newGame()
{
score = 0;
gameOver = false;
won = false;
continueAfterWin = false;
animT = 0;
pendingSpawn = false;
tiles = [];
grid = [];
for (let y = 0; y < GRID; ++y)
{
grid[y] = [];
for (let x = 0; x < GRID; ++x) grid[y][x] = null;
}
addRandomTile();
addRandomTile();
}
function boardWorldSize()
{
return GRID * CELL_SIZE + (GRID + 1) * GAP;
}
function cellCenterWorld(x, y)
{
const s = boardWorldSize();
const o = -s / 2;
return vec2(
o + GAP + CELL_SIZE / 2 + x * (CELL_SIZE + GAP),
o + GAP + CELL_SIZE / 2 + (GRID - 1 - y) * (CELL_SIZE + GAP)
);
}
function empties()
{
const e = [];
for (let y = 0; y < GRID; ++y)
for (let x = 0; x < GRID; ++x)
if (!grid[y][x]) e.push([x, y]);
return e;
}
function addRandomTile()
{
const e = empties();
if (!e.length) return false;
const [x, y] = e[(Math.random() * e.length) | 0];
const v = Math.random() < .9 ? 2 : 4;
const t = makeTile(v, x, y);
t.spawnT = SPAWN_TIME;
grid[y][x] = t;
tiles.push(t);
sSpawn.play();
return true;
}
function canMove()
{
for (let y = 0; y < GRID; ++y)
for (let x = 0; x < GRID; ++x)
{
const t = grid[y][x];
if (!t) return true;
const r = grid[y][x + 1], d = grid[y + 1] && grid[y + 1][x];
if (r && r.value === t.value) return true;
if (d && d.value === t.value) return true;
}
return false;
}
// Process one row/column of tiles in travel order (front-most first).
// Mutates tile.value / tile.pendingMerge / tile.dying as merges resolve.
// Returns each surviving tile's destination index within the line.
function processLine(line, mergedRef)
{
const result = [];
let i = 0;
while (i < line.length)
{
const a = line[i];
const b = line[i + 1];
if (b && b.value === a.value)
{
a.value *= 2;
a.pendingMerge = true;
b.dying = true;
score += a.value;
mergedRef.merged = true;
if (a.value >= 2048 && !won) { won = true; sWin.play(); }
result.push({tile: a, dst: result.length, absorbed: b});
i += 2;
}
else
{
result.push({tile: a, dst: result.length});
i += 1;
}
}
return result;
}
function applyMove(dir)
{
if (gameOver) return;
if (won && !continueAfterWin) return;
if (animT > 0) return; // ignore input while a slide is in flight
let anyMoved = false;
const mergedRef = {merged: false};
const horizontal = dir === 'L' || dir === 'R';
const forward = dir === 'L' || dir === 'U'; // travel toward grid-coord 0
for (let outer = 0; outer < GRID; ++outer)
{
// Collect tiles in travel order along this row/column
const line = [];
for (let i = 0; i < GRID; ++i)
{
const inner = forward ? i : GRID - 1 - i;
const t = horizontal ? grid[outer][inner] : grid[inner][outer];
if (t) line.push(t);
}
const result = processLine(line, mergedRef);
for (const r of result)
{
const dstAlong = forward ? r.dst : GRID - 1 - r.dst;
const newX = horizontal ? dstAlong : outer;
const newY = horizontal ? outer : dstAlong;
if (r.tile.gx !== newX || r.tile.gy !== newY) anyMoved = true;
r.tile.gx = newX;
r.tile.gy = newY;
if (r.absorbed)
{
r.absorbed.gx = newX;
r.absorbed.gy = newY;
anyMoved = true;
}
}
}
if (!anyMoved) return;
// Rebuild grid pointers from the new (gx, gy) on surviving tiles
for (let y = 0; y < GRID; ++y)
for (let x = 0; x < GRID; ++x) grid[y][x] = null;
for (const t of tiles)
{
if (t.dying) continue;
grid[t.gy][t.gx] = t;
}
// Capture each tile's current animated position as the slide's start point
for (const t of tiles) { t.srcX = t.ax; t.srcY = t.ay; }
animT = SLIDE_TIME;
pendingSpawn = true;
if (mergedRef.merged) sMerge.play();
else sMove.play();
best = max(best, score);
localStorage.setItem('ljs2048_best', best);
}
function updateAnimations()
{
if (animT > 0)
{
animT -= timeDelta;
if (animT <= 0)
{
// Slide complete: snap, resolve merges, spawn next tile, check end
animT = 0;
tiles = tiles.filter(t => !t.dying);
for (const t of tiles)
{
t.ax = t.srcX = t.gx;
t.ay = t.srcY = t.gy;
if (t.pendingMerge)
{
t.pendingMerge = false;
t.shownValue = t.value;
t.mergeT = MERGE_POP_TIME;
}
}
if (pendingSpawn)
{
pendingSpawn = false;
addRandomTile();
if (!canMove()) { gameOver = true; sLose.play(); }
}
}
else
{
const p = 1 - animT / SLIDE_TIME;
const eased = p * (2 - p); // ease-out quad — fast start, soft landing
for (const t of tiles)
{
t.ax = lerp(t.srcX, t.gx, eased);
t.ay = lerp(t.srcY, t.gy, eased);
}
}
}
for (const t of tiles)
{
if (t.spawnT > 0) t.spawnT = max(0, t.spawnT - timeDelta);
if (t.mergeT > 0) t.mergeT = max(0, t.mergeT - timeDelta);
}
}
function readMoveInput()
{
if (animT > 0) return; // input locked during slide
if (keyWasPressed('ArrowLeft') || keyWasPressed('KeyA')) return 'L';
if (keyWasPressed('ArrowRight') || keyWasPressed('KeyD')) return 'R';
if (keyWasPressed('ArrowUp') || keyWasPressed('KeyW')) return 'U';
if (keyWasPressed('ArrowDown') || keyWasPressed('KeyS')) return 'D';
if (mouseWasPressed(0))
{
swipeStartScreen = mousePosScreen.copy();
swipeArmed = true;
}
if (swipeArmed && mouseWasReleased(0))
{
swipeArmed = false;
const d = mousePosScreen.subtract(swipeStartScreen);
const ax = abs(d.x), ay = abs(d.y);
const minSwipe = 40;
if (max(ax, ay) < minSwipe) return;
if (ax > ay) return d.x < 0 ? 'L' : 'R';
return d.y < 0 ? 'U' : 'D';
}
}
///////////////////////////////////////////////////////////////////////////////
function gameUpdate()
{
updateAnimations();
if (keyWasPressed('KeyR')) newGame();
if (won && !continueAfterWin && keyWasPressed('KeyC')) continueAfterWin = true;
const dir = readMoveInput();
if (dir) applyMove(dir);
}
///////////////////////////////////////////////////////////////////////////////
function gameUpdatePost()
{
cameraPos = vec2(0, 0);
const s = boardWorldSize();
const margin = 1.1;
const viewPixels = min(mainCanvasSize.x, mainCanvasSize.y * 0.78);
cameraScale = viewPixels / (s + margin * 2);
}
///////////////////////////////////////////////////////////////////////////////
function tileFillColor(v)
{
const p = clamp((Math.log2(v) - 1) / 11, 0, 1);
const hue = .12 - .10 * p;
const sat = .55 + .25 * p;
const lit = .80 - .38 * p;
return hsl(hue, sat, lit);
}
function tileTextColor(v)
{
return v <= 4 ? hsl(0, 0, .15) : hsl(0, 0, .98);
}
function gameRender()
{
drawRect(cameraPos, vec2(200), hsl(0, 0, .09));
const boardSize = boardWorldSize();
drawRect(vec2(0, 0), vec2(boardSize), hsl(0, 0, .18));
for (let y = 0; y < GRID; ++y)
for (let x = 0; x < GRID; ++x)
drawRect(cellCenterWorld(x, y), vec2(CELL_SIZE), hsl(0, 0, .25));
// Dying tiles render under their absorber so the new value isn't revealed
// until the slide finishes
const sorted = tiles.slice().sort((a, b) => (a.dying ? 0 : 1) - (b.dying ? 0 : 1));
for (const t of sorted)
{
const c = cellCenterWorld(t.ax, t.ay);
let scale = 1;
if (t.spawnT > 0)
scale = smoothStep(1 - t.spawnT / SPAWN_TIME);
if (t.mergeT > 0)
scale *= 1 + .18 * (t.mergeT / MERGE_POP_TIME);
const size = vec2(CELL_SIZE * .92 * scale);
drawRect(c, size, tileFillColor(t.shownValue));
if (scale > .35)
{
const digits = ('' + t.shownValue).length;
const textSize = clamp(.52 - .07 * (digits - 1), .24, .52) * scale;
drawText(
'' + t.shownValue,
c.add(vec2(0, -textSize * .06)),
textSize,
tileTextColor(t.shownValue),
.08,
hsl(0, 0, .05)
);
}
}
}
///////////////////////////////////////////////////////////////////////////////
function gameRenderPost()
{
const topY = 54;
drawTextScreen('2048', vec2(86, topY), 64, hsl(.12, .7, .9), 6, hsl(0, 0, 0));
drawTextScreen(`Score: ${score}`, vec2(mainCanvasSize.x / 2, topY), 34, hsl(0, 0, 1), 4, hsl(0, 0, 0));
drawTextScreen(`Best: ${best}`, vec2(mainCanvasSize.x - 110, topY), 28, hsl(0, 0, .9), 4, hsl(0, 0, 0));
drawTextScreen('Arrows/WASD or swipe · R = restart', vec2(mainCanvasSize.x / 2, mainCanvasSize.y - 22), 20, hsl(0, 0, .8), 3, hsl(0, 0, 0));
if (won && !continueAfterWin)
{
drawRect(vec2(mainCanvasSize.x / 2, mainCanvasSize.y / 2), mainCanvasSize, hsl(0, 0, 0, .55), 0, false, true);
drawTextScreen('You made 2048!', vec2(mainCanvasSize.x / 2, mainCanvasSize.y / 2 - 30), 56, hsl(.25, .7, .9), 6, hsl(0, 0, 0));
drawTextScreen('Press C to keep going', vec2(mainCanvasSize.x / 2, mainCanvasSize.y / 2 + 28), 28, hsl(0, 0, 1), 4, hsl(0, 0, 0));
}
if (gameOver)
{
drawRect(vec2(mainCanvasSize.x / 2, mainCanvasSize.y / 2), mainCanvasSize, hsl(0, 0, 0, .65), 0, false, true);
drawTextScreen('Game Over', vec2(mainCanvasSize.x / 2, mainCanvasSize.y / 2 - 18), 64, hsl(0, 0, 1), 6, hsl(0, 0, 0));
drawTextScreen('Press R to restart', vec2(mainCanvasSize.x / 2, mainCanvasSize.y / 2 + 36), 28, hsl(0, 0, .9), 4, hsl(0, 0, 0));
}
}
///////////////////////////////////////////////////////////////////////////////
engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost);
</script>