-
Notifications
You must be signed in to change notification settings - Fork 1
/
tetris.js
392 lines (336 loc) · 11.5 KB
/
tetris.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
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
var Vector;
var console;
var HTMLElement;
/* Scheme of game display
<div id="tetris" class="tetris">
<table class="well" style="color: darkgrey;">
<tbody class="well">...</tbody>
</table>
<button class="pause" onclick='board.toggleRun()'>
pause
</button>
</div>
*/
var Board = (function () {
"use strict";
// extend standard Object with helper function
// picks random element within enumerable attribute
Object.prototype.pickRandomEnum = function () {
var keys = Object.keys(this);
return this[keys[Math.floor(Math.random() * (keys.length))]];
};
Array.prototype.all = function (f) {
return this.reduce(function (b, x) {
return b && f(x);
}, true);
};
HTMLElement.prototype.appendNewChild = function (type) {
var child = document.createElement(type);
this.appendChild(child);
return child;
};
/*
coordinates origin is left bottom.
it is form of well, (floor, walls but no ceiling)
width and height indicates size of well.
so that height != well height == infinite
*/
// constructor
// w: well width
// h: visible well height
// div: division id to print game on
function Board(w, h, div, keymap) {
var wtbl, pbtn;
this.width = w;
this.height = h;
// allocate the cells, initialize as empty
// FIXME don't need to allocate'em all, we can allocate as we need them.
this.cells = [];
this.resizeWell(this.height);
// Note. the first point of block is the anchor for rotation
// caution needed when modifying block.
this.block = undefined;
this.genRandomNow();
this.divid = div || "tetris";
div = document.getElementById(this.divid);
if (!div) {
console.log('could not find DOM element named "' + this.divid + '"');
console.assert(div);
}
// set html structure
div.className = "tetris";
wtbl = div.appendNewChild("table");
wtbl.className = "well";
wtbl.appendNewChild("tbody");
pbtn = div.appendNewChild("button");
pbtn.className = "pause";
pbtn.textContent = "run";
pbtn.onclick = this.toggleRun.bind(this);
this.handle = null;
this.getElem().setAttribute("tabindex", 0);
this.keyListener = null;
this.registerKeymap(keymap);
}
// static standard tiles
Board.prototype.fillCode = 0x25A0;
Board.prototype.emptyCode = 0x25A1;
// static standard block forms
// the first point is the anchor for rotation
Board.prototype.blocks = {
"O": [
new Vector( 0, 0),
new Vector(-1, 0),
new Vector(-1, 1),
new Vector( 0, 1)
],
"I": [
new Vector( 0, 0),
new Vector(-2, 0),
new Vector(-1, 0),
new Vector( 1, 0)
],
"L": [
new Vector(0, 0),
new Vector(0, 1),
new Vector(1, 0),
new Vector(2, 0)
],
"5": [
new Vector( 0, 0),
new Vector(-1, 0),
new Vector( 0, 1),
new Vector( 1, 1)
],
"S": [
new Vector( 0, 0),
new Vector( 1, 0),
new Vector( 0, 1),
new Vector(-1, 1)
],
random: undefined
};
// this function is not enumerable
// return new copy of randomly pick blocks
// FIXME this function is dangerous, it returns shallow copy of vector array
// when using return value of this function, it should be read - only.
Object.defineProperty(Board.prototype.blocks, "random", {
value: function () {
return Board.prototype.blocks.pickRandomEnum().slice();
},
enumerable: false
});
// default keymap for interacte with game
Board.prototype.defaultKeymap = {
39: "right", // Right arrow
37: "left", // Left arrow
40: "down", // Down arrow
38: "up", // Up arrow -- only for debugging purpose
82: "rotate", // 'R'
85: "etator" // 'U'
};
// check if you can fill the position (assuming infinite height)
Board.prototype.oktoFill = function (v) {
if (0 <= v.x && v.x < this.width && 0 <= v.y) {
return this.cells.length <= v.y || !this.cells[v.y][v.x];
}
return false;
};
// move nowBlock by amount of `v`
// returns if move was successful, nothing changes if false.
Board.prototype.moveNow = function (move) {
var laterBlock, ok;
ok = this.oktoFill.bind(this);
laterBlock = this.nowBlock.slice().map(function (v) {
// v should be used READ ONLY
var m = v.add(move);
return ok(m) ? m : null;
});
if (laterBlock.all(function (v) {
return v !== null;
})) {
this.nowBlock = laterBlock;
return true;
} else {
return false;
}
};
Board.prototype.rotateNow = function (dir) {
var laterBlock, anchor;
dir /= Math.abs(dir);
anchor = this.nowBlock[0].copy();
laterBlock = this.nowBlock.slice().map(function (v) {
// v should be READ ONLY
v = v.subtract(anchor);
v.y = -[v.x, v.x = v.y][0]; // swap
return v.multiplyBy(dir).addTo(anchor);
});
if (laterBlock.all(this.oktoFill.bind(this))) {
this.nowBlock = laterBlock;
return true;
} else {
return false;
}
};
Board.prototype.registerKeymap = function (keymap) {
var thos = this;
keymap = this.keymap = keymap || this.defaultKeymap;
// FIXME these should be private function
// but they don't have to be evaluated at every
// invocation of registerKeymap function
function mv(x, y) {
if (thos.moveNow(new Vector(x, y))) {
thos.print();
}
}
function rt(d) {
if (thos.rotateNow(d)) {
thos.print();
}
}
if (this.keyListener !== null) {
document.removeEventListener('keydown', this.keyListener, false);
}
this.keyListener = (function (event) {
switch (this.keymap[event.keyCode]) {
case "right":
mv(1, 0);
break;
case "left":
mv(-1, 0);
break;
case "down":
mv(0, -1);
break;
//case "up": // for debug purpose only
// mv(0, 1);
// break;
case "rotate":
rt(1);
break;
case "etator":
rt(-1);
break;
}
}).bind(this);
document.addEventListener('keydown', this.keyListener, false);
};
// spawn random nowBlock at top of the field.
// TODO need to check game over
Board.prototype.genRandomNow = function () {
// FIXME spawn.y should be movable
var spawnPoint = new Vector(this.width / 2, this.height - 1);
// array of currently movable cells (aka block)
this.nowBlock = this.blocks.random().map(function (v) {
return v.add(spawnPoint);
});
};
// extend height of well by h
Board.prototype.resizeWell = function (h) {
var from, to, j, i;
from = this.cells.length;
to = h + this.cells.length;
for (j = from; j < to; j += 1) {
this.cells[j] = [];
for (i = 0; i < this.width; i += 1) {
this.cells[j][i] = false;
}
}
};
Board.prototype.step = function () {
var cells, need, row, ext;
if (!this.moveNow(new Vector(0, -1))) { // nowhere to down
// stack the current block
cells = this.cells;
ext = this.resizeWell.bind(this);
this.nowBlock.forEach(function (v) {
if (cells.length <= v.y) { // need more
ext(v.y - cells.length + 1);
}
cells[v.y][v.x] = true;
});
// erase full rows
this.cells = cells.filter(function (bs) {
return !bs.all(function (b) {
return b;
});
});
// FIXME I have to keep the size since `print` rely on cells
if (this.cells.length < this.height) {
this.resizeWell(this.height - this.cells.length);
}
// gen new block
this.genRandomNow();
}
this.print();
};
// find HTMLElement among children of `divid.
// .[name] indicates class name
// [name] indicates tag name
// sequence of names indicate descendants
// Note. each step of descendant search uses 'maximum munch' policy
Board.prototype.getElem = function (sels) {
var now = document.getElementById(this.divid);
if (sels === undefined) return now;
sels.split(' ').forEach(function (sel) {
switch (sel[0]) {
case '.': // class
now = now.getElementsByClassName(sel.slice(1))[0];
break;
default: // tag
now = now.getElementsByTagName(sel)[0];
break;
}
});
return now;
};
// print board to page
Board.prototype.print = function () {
var i, j, oldWell, newWell, tr, td, fc, h, ok;
newWell = document.createElement("tbody");
newWell.className = "well";
// stacked blocks
for (j = this.height - 1; j >= 0; j -= 1) {
tr = document.createElement("tr");
for (i = 0; i < this.width; i += 1) {
td = document.createElement("td");
var code = this.cells[j][i] ? this.fillCode : this.emptyCode;
td.textContent = String.fromCharCode(code);
tr.appendChild(td);
}
newWell.appendChild(tr);
}
// current block
fc = String.fromCharCode(this.fillCode);
h = this.height;
ok = this.oktoFill.bind(this);
this.nowBlock.forEach(function (v, i) {
if (ok(v) && v.y < h) {
newWell.children[h - 1 - v.y].children[v.x].textContent = fc;
if (i == 0) {
newWell.children[h - 1 - v.y].children[v.x].style.color = "red";
}
}
});
this.getElem(".well tbody").replaceWith(newWell);
};
Board.prototype.toggleRun = function () {
if (this.handle === null) {
this.getElem(".pause").textContent = "pause";
this.getElem(".well").style.color = "black";
this.handle = window.setInterval(this.step.bind(this), 1000);
} else {
window.clearInterval(this.handle);
this.handle = null;
this.getElem(".well").style.color = "darkgrey";
this.getElem(".pause").textContent = "run";
}
};
return Board;
}());
/* reference to look for candidate tile character
https://en.wikipedia.org/wiki/Geometric_Shapes#Font_coverage
https://en.wikipedia.org/wiki/Block_Elements
https://en.wikipedia.org/wiki/Box_Drawing
https://en.wikipedia.org/wiki/Semigraphics
https://en.wikipedia.org/wiki/Tombstone_(typography)
*/