-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfour.js
More file actions
414 lines (357 loc) · 9.09 KB
/
four.js
File metadata and controls
414 lines (357 loc) · 9.09 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
// The width of the canvas.
let width;
// The height of the canvas.
let height;
// Set the grid dimensions.
const gridMaxX = 4;
const gridMaxY = 4;
// The game grid.
let grid = [];
// The game loop timer ID.
let gameloopId;
// Define animation settings.
let frameCounter = 0;
let frames = [];
// The current score.
let score = 0;
// The canvas context object.
let ctx;
// Set up delta times.
let lastUpdate = Date.now();
const updateLoopsPerSecond = 1000 / 60;
let delta = 0;
// Constants for detecting directions.
const KEYPRESS_UP = 'up';
const KEYPRESS_DOWN = 'down';
const KEYPRESS_LEFT = 'left';
const KEYPRESS_RIGHT = 'right';
// Define the characters to display.
const numbers = [];
numbers[' '] = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
];
numbers[0] = [
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 0, 0, 1],
[1, 1, 1, 1],
];
numbers[1] = [
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0],
];
numbers[2] = [
[0, 1, 1, 0],
[1, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 1, 1],
];
numbers[3] = [
[1, 1, 1, 0],
[0, 1, 1, 1],
[0, 0, 0, 1],
[1, 1, 1, 0],
];
numbers[4] = [
[1, 0, 0, 0],
[1, 0, 1, 0],
[1, 1, 1, 1],
[0, 0, 1, 0],
];
numbers[5] = [
[1, 1, 1, 1],
[1, 1, 0, 0],
[0, 0, 1, 0],
[1, 1, 1, 0],
];
numbers[6] = [
[0, 1, 1, 0],
[1, 0, 0, 0],
[1, 1, 1, 0],
[1, 1, 1, 0],
];
numbers[7] = [
[1, 1, 1, 1],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0],
];
numbers[8] = [
[0, 1, 1, 0],
[1, 1, 1, 1],
[1, 0, 0, 1],
[0, 1, 1, 0],
];
numbers[9] = [
[0, 1, 1, 1],
[0, 1, 0, 1],
[0, 1, 1, 1],
[0, 0, 0, 1],
];
// Set up the game grid.
function setupGrid() {
grid = [];
for (let i = 0; i < gridMaxX; i += 1) {
grid[i] = [];
column = 0;
const yCoord = i * (width / gridMaxY);
for (let j = 0; j < gridMaxY; j += 1) {
const xCoord = j * (width / gridMaxY);
const rectWidth = width / gridMaxY;
const rectHeight = height / gridMaxY;
grid[i][j] = {
column: j,
row: i,
x: xCoord,
y: yCoord,
width: rectWidth,
height: rectHeight,
};
}
}
return grid;
}
// Draw the grid.
function drawGrid() {
for (let i = 0; i < gridMaxX; i += 1) {
const y = i * (width / gridMaxY);
for (let j = 0; j < gridMaxY; j += 1) {
const x = j * (width / gridMaxY);
const rectWidth = width / gridMaxY;
const rectHeight = height / gridMaxY;
ctx.strokeRect(x, y, rectWidth, rectHeight);
}
}
}
// Fix a box with a colour.
function fillBox(box, colour) {
ctx.beginPath();
ctx.fillStyle = colour;
ctx.fillRect(box.x, box.y, box.width, box.height);
}
// Clear the screen and redraw the grid.
function cls() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGrid();
}
// Flash the game area with a colour and re-draw the grid.
function flashGrid(colour) {
ctx.beginPath();
ctx.fillStyle = colour;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// After some milliseconds, clear the screen and re-draw the grid.
clearInterval(gameloopId);
setTimeout(() => {
cls();
lastUpdate = Date.now();
gameloopId = setInterval(gameLoop, updateLoopsPerSecond);
}, 250);
}
// Handle the canvas click event and pass onto a custom handle function
// along the box that was clicked.
function canvasClick(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
// Collision detection between clicked offset and element.
for (let i = 0; i < gridMaxX; i += 1) {
for (let j = 0; j < gridMaxY; j += 1) {
const element = grid[i][j];
if (
y > element.y
&& y < element.y + element.height
&& x > element.x
&& x < element.x + element.width
) {
if (typeof userActionClick === 'function') {
userActionClick(element);
}
return false;
}
}
}
return false;
}
// Add event listener for mouse click events.
function addClickListener() {
canvas.addEventListener('click', canvasClick, false);
}
// Remove the event listener for mouse click events.
function removeClickListener() {
canvas.removeEventListener('click', canvasClick, false);
}
// Convert the keypress into directions and pass them upstream.
function keyPress(event) {
if (typeof userActionKeyPress !== 'function') {
return;
}
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].indexOf(event.code) > -1) {
event.preventDefault();
}
switch (event.code) {
case 'ArrowLeft':
case 'KeyA':
userActionKeyPress(KEYPRESS_LEFT);
break;
case 'ArrowUp':
case 'KeyW':
userActionKeyPress(KEYPRESS_UP);
break;
case 'ArrowRight':
case 'KeyD':
userActionKeyPress(KEYPRESS_RIGHT);
break;
case 'ArrowDown':
case 'KeyS':
userActionKeyPress(KEYPRESS_DOWN);
break;
default:
// Do nothing.
}
}
// Add an event listener for key down events.
function addKeyListener() {
document.addEventListener('keydown', keyPress, false);
}
// Remove the event listener for key down events.
function removeKeyListener() {
document.removeEventListener('keydown', keyPress, false);
}
// Shuffle an array.
function shuffle(array) {
let currentIndex = array.length;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
const randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
}
// Generate a random number between two values.
function randomRange(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// Get a random element from the grid.
function randomElement() {
const randomX = Math.floor(Math.random() * gridMaxX);
const randomY = Math.floor(Math.random() * gridMaxY);
return grid[randomX][randomY];
}
// Internal function used to animate the score.
function animateScore() {
cls();
if (frameCounter >= frames.length) {
// Finished animating.
frames = [];
flashGrid('black');
addKeyListener();
addClickListener();
return;
}
for (let i = 0; i < frames[frameCounter].length; i += 1) {
for (let j = 0; j < frames[frameCounter][i].length; j += 1) {
if (frames[frameCounter][i][j] === 1) {
// Yes, we use j and i backwards here as we want to
// print the text scrolling across, rather than up.
fillBox(grid[j][i], 'black');
}
}
}
frameCounter += 1;
setTimeout(animateScore, 250);
}
// Display the score in the game grid.
function displayScore(passedScore) {
removeKeyListener();
removeClickListener();
// Function to find the colomn from the grid.
const arrayColumn = (arr, n) => arr.map((x) => x[n]);
// Convert score into a string and add start and end buffers.
const scoreString = ` ${passedScore.toString()} `;
const convertedScore = [];
for (let i = 0; i < scoreString.length; i += 1) {
const character = numbers[scoreString[i]];
for (let j = 0; j < character[0].length; j += 1) {
convertedScore.push(arrayColumn(character, j));
}
if (scoreString[i] !== ' ') {
// Single row buffer between each character.
convertedScore.push([0, 0, 0, 0]);
}
}
// Convert string into an array of elements.
for (let i = 0; i < convertedScore.length - 4; i += 1) {
const frame = [];
frame.push(convertedScore[i]);
frame.push(convertedScore[i + 1]);
frame.push(convertedScore[i + 2]);
frame.push(convertedScore[i + 3]);
frames.push(frame);
}
frameCounter = 0;
setTimeout(animateScore, 250);
}
// The game loop, where we define our custom functions.
function gameLoop() {
// Frames having length means that our animation is running.
if (frames.length === 0) {
let now = Date.now();
delta = (now - lastUpdate) / 1000;
lastUpdate = now;
draw(delta);
update(delta);
}
drawGrid();
}
// Initialise the canvas.
function initCanvas(id) {
canvas = document.getElementById(id);
canvas.style.cursor = 'crosshair';
canvas.style.background = 'white';
canvas.style.border = '2px solid black';
canvas.style.margin = '0 auto 0 auto';
canvas.style.display = 'flex';
ctx = canvas.getContext('2d');
width = canvas.width;
height = canvas.height;
addClickListener();
addKeyListener();
setupGrid();
drawGrid();
if (typeof init === 'function') {
init();
}
gameloopId = setInterval(gameLoop, updateLoopsPerSecond);
}
// Pause the game loop for a number of seconds and restart it.
function wait(seconds) {
clearInterval(gameloopId);
setTimeout(() => {
lastUpdate = Date.now();
gameloopId = setInterval(gameLoop, updateLoopsPerSecond);
}, seconds);
}
// Get the canvas context object of the game grid. Used for testing.
function getCanvasContextObject() {
return ctx;
}
// Load in the canvas element and set up the game.
window.onload = function fourWindowLoad() {
initCanvas('four');
};
if (typeof module === 'object') {
module.exports = {
getCanvasContextObject,
setupGrid,
drawGrid,
initCanvas,
};
}