forked from jakesgordon/javascript-tetris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
622 lines (575 loc) · 17.7 KB
/
index.html
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
<!DOCTYPE html>
<html>
<head>
<title>Javascript Tetris</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="tetris">
<div id="menu">
<p class="header" id="start">
<a href="javascript:play();">Press Space to Play</a>
</p>
<p><canvas id="upcoming"></canvas></p>
<p>score <span id="score">00000</span></p>
<p>rows <span id="rows">0</span></p>
<hr />
<p class="header">Options</p>
<input type="checkbox" id="showGrid" name="showGrid" value="showGrid" />
<label class="option" for="showGrid">Show grid</label><br />
</div>
<canvas id="canvas">
Sorry, this example cannot be run because your browser does not support
the <canvas> element
</canvas>
</div>
<script src="stats.js"></script>
<script>
//-------------------------------------------------------------------------
// base helper methods
//-------------------------------------------------------------------------
function get(id) {
return document.getElementById(id);
}
function hide(id) {
get(id).style.visibility = "hidden";
}
function show(id) {
get(id).style.visibility = null;
}
function html(id, html) {
get(id).innerHTML = html;
}
function timestamp() {
return new Date().getTime();
}
function random(min, max) {
return min + Math.random() * (max - min);
}
function randomChoice(choices) {
return choices[Math.round(random(0, choices.length - 1))];
}
if (!window.requestAnimationFrame) {
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimationFrame =
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback, element) {
window.setTimeout(callback, 1000 / 60);
};
}
//-------------------------------------------------------------------------
// game constants
//-------------------------------------------------------------------------
var KEY = { ESC: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 },
DIR = { UP: 0, RIGHT: 1, DOWN: 2, LEFT: 3, MIN: 0, MAX: 3 },
stats = new Stats(),
canvas = get("canvas"),
ctx = canvas.getContext("2d"),
ucanvas = get("upcoming"),
uctx = ucanvas.getContext("2d"),
speed = { start: 0.6, decrement: 0.005, min: 0.1 }, // how long before piece drops by 1 row (seconds)
nx = 10, // width of tetris court (in blocks)
ny = 20, // height of tetris court (in blocks)
nu = 5; // width/height of upcoming preview (in blocks)
//-------------------------------------------------------------------------
// game variables (initialized during reset)
//-------------------------------------------------------------------------
var dx,
dy, // pixel size of a single tetris block
blocks, // 2 dimensional array (nx*ny) representing tetris court - either empty block or occupied by a 'piece'
actions, // queue of user actions (inputs)
playing, // true|false - game is in progress
dt, // time since starting this game
current, // the current piece
next, // the next piece
score, // the current score
vscore, // the currently displayed score (it catches up to score in small chunks - like a spinning slot machine)
rows, // number of completed rows in the current game
step; // how long before current piece drops by 1 row
//-------------------------------------------------------------------------
// tetris pieces
//
// blocks: each element represents a rotation of the piece (0, 90, 180, 270)
// each element is a 16 bit integer where the 16 bits represent
// a 4x4 set of blocks, e.g. j.blocks[0] = 0x44C0
//
// 0100 = 0x4 << 3 = 0x4000
// 0100 = 0x4 << 2 = 0x0400
// 1100 = 0xC << 1 = 0x00C0
// 0000 = 0x0 << 0 = 0x0000
// ------
// 0x44C0
//
//-------------------------------------------------------------------------
var i = {
size: 4,
blocks: [0x0f00, 0x2222, 0x00f0, 0x4444],
color: "cyan",
};
var j = {
size: 3,
blocks: [0x44c0, 0x8e00, 0x6440, 0x0e20],
color: "blue",
};
var l = {
size: 3,
blocks: [0x4460, 0x0e80, 0xc440, 0x2e00],
color: "orange",
};
var o = {
size: 2,
blocks: [0xcc00, 0xcc00, 0xcc00, 0xcc00],
color: "yellow",
};
var s = {
size: 3,
blocks: [0x06c0, 0x8c40, 0x6c00, 0x4620],
color: "green",
};
var t = {
size: 3,
blocks: [0x0e40, 0x4c40, 0x4e00, 0x4640],
color: "purple",
};
var z = {
size: 3,
blocks: [0x0c60, 0x4c80, 0xc600, 0x2640],
color: "red",
};
//------------------------------------------------
// do the bit manipulation and iterate through each
// occupied block (x,y) for a given piece
//------------------------------------------------
function eachblock(type, x, y, dir, fn) {
var bit,
result,
row = 0,
col = 0,
blocks = type.blocks[dir];
for (bit = 0x8000; bit > 0; bit = bit >> 1) {
if (blocks & bit) {
fn(x + col, y + row);
}
if (++col === 4) {
col = 0;
++row;
}
}
}
//-----------------------------------------------------
// check if a piece can fit into a position in the grid
//-----------------------------------------------------
function occupied(type, x, y, dir) {
var result = false;
eachblock(type, x, y, dir, function (x, y) {
if (x < 0 || x >= nx || y < 0 || y >= ny || getBlock(x, y))
result = true;
});
return result;
}
function unoccupied(type, x, y, dir) {
return !occupied(type, x, y, dir);
}
//-----------------------------------------
// start with 4 instances of each piece and
// pick randomly until the 'bag is empty'
//-----------------------------------------
var pieces = [];
function randomPiece() {
if (pieces.length == 0)
pieces = [
i,
i,
i,
i,
j,
j,
j,
j,
l,
l,
l,
l,
o,
o,
o,
o,
s,
s,
s,
s,
t,
t,
t,
t,
z,
z,
z,
z,
];
var type = pieces.splice(random(0, pieces.length - 1), 1)[0];
return {
type: type,
dir: DIR.UP,
x: Math.round(random(0, nx - type.size)),
y: 0,
};
}
//-------------------------------------------------------------------------
// GAME LOOP
//-------------------------------------------------------------------------
function run() {
showStats(); // initialize FPS counter
addEvents(); // attach keydown and resize events
var last = (now = timestamp());
var gridDrawnOnce = false;
function frame() {
now = timestamp();
update(Math.min(1, (now - last) / 1000.0)); // using requestAnimationFrame have to be able to handle large delta's caused when it 'hibernates' in a background or non-visible tab
draw();
if (document.getElementById("showGrid").checked && !gridDrawnOnce) {
drawGrid();
gridDrawnOnce = true;
} else if (!document.getElementById("showGrid").checked && !playing) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
gridDrawnOnce = false;
}
stats.update();
last = now;
requestAnimationFrame(frame, canvas);
}
resize(); // setup all our sizing information
reset(); // reset the per-game variables
frame(); // start the first frame
}
var lastCheckboxState = document.getElementById("showGrid").checked;
function showStats() {
stats.domElement.id = "stats";
get("menu").appendChild(stats.domElement);
}
function addEvents() {
document.addEventListener("keydown", keydown, false);
window.addEventListener("resize", resize, false);
}
function resize(event) {
canvas.width = canvas.clientWidth; // set canvas logical size equal to its physical size
canvas.height = canvas.clientHeight; // (ditto)
ucanvas.width = ucanvas.clientWidth;
ucanvas.height = ucanvas.clientHeight;
dx = canvas.width / nx; // pixel size of a single tetris block
dy = canvas.height / ny; // (ditto)
invalidate();
invalidateNext();
}
function keydown(ev) {
var handled = false;
if (playing) {
switch (ev.keyCode) {
case KEY.LEFT:
actions.push(DIR.LEFT);
handled = true;
break;
case KEY.RIGHT:
actions.push(DIR.RIGHT);
handled = true;
break;
case KEY.UP:
actions.push(DIR.UP);
handled = true;
break;
case KEY.DOWN:
actions.push(DIR.DOWN);
handled = true;
break;
case KEY.ESC:
lose();
handled = true;
break;
}
} else if (ev.keyCode == KEY.SPACE) {
play();
handled = true;
}
if (handled) ev.preventDefault(); // prevent arrow keys from scrolling the page (supported in IE9+ and all other browsers)
}
//-------------------------------------------------------------------------
// GAME LOGIC
//-------------------------------------------------------------------------
function play() {
hide("start");
reset();
playing = true;
}
function lose() {
show("start");
setVisualScore();
playing = false;
}
function setVisualScore(n) {
vscore = n || score;
invalidateScore();
}
function setScore(n) {
score = n;
setVisualScore(n);
}
function addScore(n) {
score = score + n;
}
function clearScore() {
setScore(0);
}
function clearRows() {
setRows(0);
}
function setRows(n) {
rows = n;
step = Math.max(speed.min, speed.start - speed.decrement * rows);
invalidateRows();
}
function addRows(n) {
setRows(rows + n);
}
function getBlock(x, y) {
return blocks && blocks[x] ? blocks[x][y] : null;
}
function setBlock(x, y, type) {
blocks[x] = blocks[x] || [];
blocks[x][y] = type;
invalidate();
}
function clearBlocks() {
blocks = [];
invalidate();
}
function clearActions() {
actions = [];
}
function setCurrentPiece(piece) {
current = piece || randomPiece();
invalidate();
}
function setNextPiece(piece) {
next = piece || randomPiece();
invalidateNext();
}
function reset() {
dt = 0;
clearActions();
clearBlocks();
clearRows();
clearScore();
setCurrentPiece(next);
setNextPiece();
}
function update(idt) {
if (playing) {
if (vscore < score) setVisualScore(vscore + 1);
handle(actions.shift());
dt = dt + idt;
if (dt > step) {
dt = dt - step;
drop();
}
}
}
function handle(action) {
switch (action) {
case DIR.LEFT:
move(DIR.LEFT);
break;
case DIR.RIGHT:
move(DIR.RIGHT);
break;
case DIR.UP:
rotate();
break;
case DIR.DOWN:
drop();
break;
}
}
function move(dir) {
var x = current.x,
y = current.y;
switch (dir) {
case DIR.RIGHT:
x = x + 1;
break;
case DIR.LEFT:
x = x - 1;
break;
case DIR.DOWN:
y = y + 1;
break;
}
if (unoccupied(current.type, x, y, current.dir)) {
current.x = x;
current.y = y;
invalidate();
return true;
} else {
return false;
}
}
function rotate() {
var newdir = current.dir == DIR.MAX ? DIR.MIN : current.dir + 1;
if (unoccupied(current.type, current.x, current.y, newdir)) {
current.dir = newdir;
invalidate();
}
}
function drop() {
if (!move(DIR.DOWN)) {
addScore(10);
dropPiece();
removeLines();
setCurrentPiece(next);
setNextPiece(randomPiece());
clearActions();
if (occupied(current.type, current.x, current.y, current.dir)) {
lose();
}
}
}
function dropPiece() {
eachblock(
current.type,
current.x,
current.y,
current.dir,
function (x, y) {
setBlock(x, y, current.type);
}
);
}
function removeLines() {
var x,
y,
complete,
n = 0;
for (y = ny; y > 0; --y) {
complete = true;
for (x = 0; x < nx; ++x) {
if (!getBlock(x, y)) complete = false;
}
if (complete) {
removeLine(y);
y = y + 1; // recheck same line
n++;
}
}
if (n > 0) {
addRows(n);
addScore(100 * Math.pow(2, n - 1)); // 1: 100, 2: 200, 3: 400, 4: 800
}
}
function removeLine(n) {
var x, y;
for (y = n; y >= 0; --y) {
for (x = 0; x < nx; ++x)
setBlock(x, y, y == 0 ? null : getBlock(x, y - 1));
}
}
//-------------------------------------------------------------------------
// RENDERING
//-------------------------------------------------------------------------
var invalid = {};
function invalidate() {
invalid.court = true;
}
function invalidateNext() {
invalid.next = true;
}
function invalidateScore() {
invalid.score = true;
}
function invalidateRows() {
invalid.rows = true;
}
function draw() {
ctx.save();
ctx.lineWidth = 1;
ctx.translate(0.5, 0.5); // for crisp 1px black lines
drawCourt();
drawNext();
drawScore();
ctx.restore();
}
function drawCourt() {
if (invalid.court) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (playing)
drawPiece(ctx, current.type, current.x, current.y, current.dir);
var x, y, block;
for (y = 0; y < ny; y++) {
for (x = 0; x < nx; x++) {
if ((block = getBlock(x, y))) drawBlock(ctx, x, y, block.color);
}
}
ctx.strokeRect(0, 0, nx * dx - 1, ny * dy - 1); // court boundary
invalid.court = false;
if (document.getElementById("showGrid").checked) {
drawGrid();
}
}
}
function drawNext() {
if (invalid.next) {
var padding = (nu - next.type.size) / 2; // half-arsed attempt at centering next piece display
uctx.save();
uctx.translate(0.5, 0.5);
uctx.clearRect(0, 0, nu * dx, nu * dy);
drawPiece(uctx, next.type, padding, padding, next.dir);
uctx.strokeStyle = "black";
uctx.strokeRect(0, 0, nu * dx - 1, nu * dy - 1);
uctx.restore();
invalid.next = false;
}
}
function drawScore() {
if (invalid.score) {
html("score", ("00000" + Math.floor(vscore)).slice(-5));
invalid.score = false;
}
}
function drawRows() {
if (invalid.rows) {
html("rows", rows);
invalid.rows = false;
}
}
function drawGrid() {
ctx.beginPath();
ctx.strokeStyle = "rgba(0, 0, 0, 0.6)";
ctx.lineWidth = 0.5;
for (var x = 0; x <= nx; x++) {
ctx.moveTo(0.5 + x * dx, 0);
ctx.lineTo(0.5 + x * dx, ny * dy);
}
for (var y = 0; y <= ny; y++) {
ctx.moveTo(0, 0.5 + y * dy);
ctx.lineTo(nx * dx, 0.5 + y * dy);
}
ctx.stroke();
}
function drawPiece(ctx, type, x, y, dir) {
eachblock(type, x, y, dir, function (x, y) {
drawBlock(ctx, x, y, type.color);
});
}
function drawBlock(ctx, x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x * dx, y * dy, dx, dy);
ctx.strokeRect(x * dx, y * dy, dx, dy);
}
//-------------------------------------------------------------------------
// FINALLY, lets run the game
//-------------------------------------------------------------------------
run();
</script>
</body>
</html>