forked from AlwaysFr3sh2/ArcadeOne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Arcade.html
644 lines (611 loc) · 19.4 KB
/
Arcade.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
<!DOCTYPE html>
<html>
<head>
<title>Arcade One</title>
<link rel="stylesheet" type="text/css" href="arcadestyle.css">
</head>
<body>
<div>
<p>Arcade One</p>
</div>
<div style='text-align:center; justify-content: center;'>
<button onclick="runSnake()">Play Snake</button>
<button onclick="runTetris()">Play Tetris</button>
<button onclick="runBreakout()">Play Breakout</button>
<br>
</div>
<div id='box'>
<canvas width="400" height="400" id="game"></canvas>
</div>
<script>
var GameRunning = false;
class Snake {
constructor() {
this.width = 15;
this.height = 15;
this.maxSpeed = 16;
this.xspeed = 0;
this.yspeed = 0
this.cellno = 4;
this.count = 1;
// the snake is initialized at this position, changing it after initialisation will do nothing
this.position = {
//x: 4 * 16,
//y: 1 * 16
x: 16,
y: 0
}
// each array point represents a cell, here we have 4, their positioning doesn't matter
this.cells = [
[this.position.x, this.position.y],
[this.position.x + 17, 0],
[this.position.x + 34, 0],
[this.position.x + 51, 0]
];
}
// change the velocity of the snake
moveLeft() {
this.xspeed = -this.maxSpeed;
// we need to reset the other axis to prevent diagonal travel.
this.yspeed = 0;
}
moveRight() {
this.xspeed = this.maxSpeed;
this.yspeed = 0;
}
moveUp() {
this.yspeed = -this.maxSpeed;
this.xspeed = 0;
}
moveDown() {
this.yspeed = this.maxSpeed;
this.xspeed = 0
}
// draw each of the snakes cells
draw(ctx) {
for (var i = 0; i < this.cellno; i++) {
ctx.fillStyle = '#00f';
ctx.fillRect(this.cells[i][0], this.cells[i][1], this.width, this.height);
}
}
// updates the snake, delta time makes it smooth, it's not being used here though.
// delta time regulates fps on slower and fast computers.
update(deltatime)
{
if (!deltatime) return;
for (var i = this.cellno - 1; i > 0; i--) {
this.cells[i][0] = this.cells[i - 1][0];
this.cells[i][1] = this.cells[i - 1][1];
}
this.cells[0][0] += this.xspeed;
this.cells[0][1] += this.yspeed;
}
}
// contains all of the data for the apple
class Apple {
constructor() {
this.x = getRandomInt(0, 25) * 16; // we give the range as 25 then multiply
this.y = getRandomInt(0, 25) * 16; // so that the apple will be on the grid.
//this.x = 16;
//this.y = 0;
this.width = 15;
this.height = 15;
this.color = '#f00'
}
//draw the apple
draw(ctx) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
// so we can give the apple a random color if we want later
changeColor(color) {
this.color = color;
}
}
//handles the players input, calls the snake to make changes
class InputHandler {
constructor(snake) {
document.addEventListener('keydown', event => {
switch(event.keyCode) {
case 37:
if (snake.xspeed == 0){ // if the player is already moving L/R they cannot move L/R again
snake.moveLeft();
}
break;
case 39:
if (snake.xspeed == 0) {
snake.moveRight();
}
break;
case 40:
if (snake.yspeed == 0) {
snake.moveDown();
}
break;
case 38:
if (snake.yspeed == 0) {
snake.moveUp();
}
break;
}
});
}
}
// get a random integer within the given range.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
// check if the snake has eaten the apple
function checkApple(apple, snake) {
if (snake.cells[0][0] == apple.x && snake.cells[0][1] == apple.y) {
// add a new cell to the snake
snake.cells.push([[0],[0]]);
snake.cellno += 1;
apple.color == "0f0";
// give the apple a new location to simulate a new apple appearing
apple.x = getRandomInt(0,25) * 16;
apple.y = getRandomInt(0,25) * 16;
}
}
// check if the snake has collided with itself
function checkIfDead(snake,ctx) {
// if the player hits itself
for (var i = snake.cellno - 1; i > 0; i--) {
if (snake.cells[0][0] == snake.cells[i][0] && snake.cells[0][1] == snake.cells[i][1]){
window.location = 'youlose.html';
}
}
// if the player hits the boundary
if (snake.cells[0][0] < -1 || snake.cells[0][0] > 600){
//you lose
window.location = 'youlose.html';
}
if (snake.cells[0][1] < -1 || snake.cells[0][1] > 400) {
window.location = 'youlose.html';
}
}
// the 'main' function for the snake game
function runSnake() {
if (GameRunning == false) {
GameRunning = true;
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
canvas.width = "600";
canvas.height = "400";
var snake = new Snake();
var apple = new Apple();
// give the player a short delay before they lose
var delay = 100;
//loop and time stuff
new InputHandler(snake);
var lastTime = 0;
var count = 0;
function gameLoop(timestamp) {
requestAnimationFrame(gameLoop);
// slow the game down
if (++count < 4) {
return;
}
count = 0;
var deltaTime = timestamp - lastTime;
lastTime = timestamp;
// refresh the screen
ctx.clearRect(0,0,600,600);
// draw and update the snake
snake.update(deltaTime);
snake.draw(ctx);
// draw the apple
apple.draw(ctx);
// run the check apple function
checkApple(apple, snake);
// run the delay if the delay is not over.
if (delay == 0) {
checkIfDead(snake, ctx);
}
else {
delay--;
}
}
gameLoop();
}
}
function runTetris(){
if(GameRunning == false) {
GameRunning = true;
var SQ = 25; // square side in pixels
var HCOUNT = 10; // horizontal width in squares
var VCOUNT = 18; // vertical width in squares
var WIDTH = SQ * HCOUNT;
var HEIGHT = SQ * VCOUNT;
var SPEED = 250; // game speed in the loop.
var DROPSPEED = 80; // game speed when dropping objects.
var ORIGSPEED = 250; // original game speed
var BGCOLOR = '#fff';
var canvas = document.getElementById('game');
canvas.width = WIDTH;
canvas.height = HEIGHT;
var ctx = canvas.getContext('2d');
// Object definitions
// Cube, Left L, Right L, S shape, Z shape, T shape, Pipe (I)
// '0' is the normal orientation
// '1' is the object rotated 90 degrees clockwise
// '2' is the object rotated 180 degrees clockwise
// '3' is the object rotated 270 degrees clockwise
var objects = [
{ // Cube
fill: '#fcff69',
0: [[0,0], [1,1], [0,1], [1,0]], 1: [[0,0], [1,1], [0,1], [1,0]],
2: [[0,0], [1,1], [0,1], [1,0]], 3: [[0,0], [1,1], [0,1], [1,0]]
}, { // Normal L
fill: '#ffd761',
0: [[0,0],[1,0],[1,1],[1,2]], 1: [[0,1],[1,1],[2,1],[2,0]],
2: [[0,0],[0,1],[0,2],[1,2]], 3: [[0,0],[1,0],[2,0],[0,1]]
}, { // Reverse L
fill: '#617bff',
0: [[0,0],[1,0],[0,1],[0,2]], 1: [[0,0],[1,0],[2,0],[2,1]],
2: [[1,0],[1,1],[1,2],[0,2]], 3: [[0,0],[0,1],[1,1],[2,1]]
}, { // S - shaped
fill: '#6bff66',
0: [[0,1],[1,1],[1,0],[2,0]], 1: [[0,0],[0,1],[1,1],[1,2]],
2: [[0,1],[1,1],[1,0],[2,0]], 3: [[0,0],[0,1],[1,1],[1,2]]
}, { // Z - shaped
fill: '#ff5f4a',
0: [[0,0],[1,0],[1,1],[2,1]], 1: [[1,0],[1,1],[0,1],[0,2]],
2: [[0,0],[1,0],[1,1],[2,1]], 3: [[1,0],[1,1],[0,1],[0,2]]
},
{ // T - shaped
fill: '#c354ff',
0: [[0,0],[1,0],[2,0],[1,-1]], 1: [[2,0],[1,0],[1,1],[1,-1]],
2: [[0,0],[1,0],[2,0],[1,1]], 3: [[0,0],[1,0],[1,1],[1,-1]]
}, { // Pipe
fill: '#6bf8ff',
0: [[0,0], [0,1], [0,2], [0,3]], 1: [[-1,1],[0,1],[1,1],[2,1]],
2: [[0,0], [0,1], [0,2], [0,3]], 3: [[-1,1],[0,1],[1,1],[2,1]]
}
];
// current object
var object = null;
// object's orientation
var or = 2;
// last position of the object
var objectPos = [];
// horizontal position (offset) of the object
var hpos = 4;
// vertical position (offset) of the object
var vpos = 0;
// whether this is the first tick of a new object
var newOb = true;
// last tick's time
var t = new Date();
// If true the last object should be glued
var glue = false;
// The Map, Grid, Matrix .. whatever
// Note: The map has 3 types of fields (squares). Empty fields have
// value 1, fields that are occupied by the current moving object have value 2,
// and fields that are occupied by settled objects have a string value of the
// color in which they should be displayed (object's 'fill' property)
var Map = [];
function resetGame(){
for( var i = 0; i < HCOUNT; i++ ){
Map[i] = [];
for( var j = 0; j < VCOUNT; j++ )
Map[i][j] = 1;
}
glue = false, newOb = true, vpos = or = 0, hpos = 4;
}
resetGame();
// The main game logic loop
function tick() {
// Clears the map cells where the object used to be in the previous tick
var color = 1;
var removeLines = false;
if( glue ){
removeLines = true;
glue = false;
newOb = true;
color = object.fill;
vpos = 0;
hpos = 4;
or = 0;
}
for( var i=0; i < objectPos.length; i++ )
Map[ objectPos[i][0] ][ objectPos[i][1] ] = color;
objectPos = [];
removeLines && removeFullLines();
if( newOb ) {
// next random object to appear
object = objects[ Math.floor( Math.random() * objects.length ) ];
// compensates the vpos for the object's height
vpos -= Math.max( object[or][0][1], object[or][1][1], object[or][2][1], object[or][3][1] ) - 1;
}
var x, y, olength = object[or].length;
// Place the object on the map
// The object won't be out of horizontal bounds
for( i=0; i < olength; i++ ) {
x = hpos + object[or][i][0];
y = vpos + object[or][i][1];
if( Map[ x ][ y ] ) {
Map[ x ][ y ] = 2;
objectPos.push( [ x, y ] );
}
}
// Check the time difference from the last tick
// This dictates the game speed
var t1 = new Date();
if( t1 - t > SPEED ){
// if it's time for a new tick
var columns = {}
for( i=0; i < olength; i++ ) {
x = hpos + object[or][i][0];
y = vpos + object[or][i][1];
if( y<0 )
continue;
!isNaN(columns[x]) || (columns[x] = y);
columns[x] = Math.max( columns[x], y );
}
for( i in columns )
if( columns[i] == VCOUNT - 1 || Map[i][columns[i] + 1] != 1 ){
glue = true;
if( newOb ) {
document.location.reload();
}
SPEED = ORIGSPEED;
return;
}
t = t1;
vpos += 1;
}
newOb = false;
}
// Scans the map for filled lines and removes them.
function removeFullLines(){
var line, j, i, k;
for( i = VCOUNT-1; i > 0; i-- ){
line = true;
for( j=0; j < HCOUNT; j++ )
if( typeof Map[j][i] != 'string' )
line = false;
if( line ) {
for( k = i; k > 0; k-- )
for( j = 0; j < HCOUNT; j++ )
Map[j][k] = Map[j][k-1];
i++;
}
}
ORIGSPEED -= 3;
DROPSPEED -= 3;
}
// Checks if the object can be moved to the side
function canMove( side ){
var maxFunc = side == 1 ? Math.max : Math.min;
var rows = {}, x, y;
for( var i=0, olength=object[or].length; i < olength; i++ ) {
y = vpos + object[or][i][1];
x = hpos + object[or][i][0] + side; // temporarily move the object sideways
!isNaN(rows[y]) || ( rows[y] = x ); // get the leftmost/rightmost square in each row
rows[y] = maxFunc( rows[y], x );
}
// Check if the leftmost/rightmost square is in an illegal position
for( i in rows )
if( rows[i] < 0 || rows[i] > HCOUNT-1 || Map[ rows[i] ][ i ] != 1 )
return false;
return true;
}
// Checks if the element can be rotated.
function canRotate() {
var newOr = (or + 1) % 4;
var to = object[ newOr ], x, y;
for( var i=0, olength=to.length; i < olength; i++ ){
x = hpos + to[i][0];
y = vpos + to[i][1];
// If we want to rotate an object at the edge, try
// moving that object to the side to see if it can rotate.
if( !Map[x] ) {
var mod = x < 0 ? 1 : -1;
hpos += mod;
if( canRotate() ) return true;
else hpos -= mod;
}
if( !Map[x][y] || typeof Map[x][y] === 'string' )
return false;
}
return true;
}
// draws a line from point (fromx, fromy) to point (tox, toy)
function line( fromx, fromy, tox, toy ){
ctx.beginPath();
ctx.moveTo( fromx, fromy );
ctx.lineTo( tox, toy );
ctx.stroke();
}
// The grid line styles
ctx.strokeStyle = '#999';
ctx.lineWidth = .5;
function drawMap() {
// clear map and draw grid
ctx.clearRect( 0, 0, WIDTH, HEIGHT );
var currentSquare, w, h, i;
// this loop draws the current map state
for( w = 0; w < HCOUNT; w++ ){
ctx.save();
ctx.translate( w * SQ, 0 ); // Move the canvas horizontally
for( h = 0; h < VCOUNT; h++ ){
currentSquare = Map[w][h];
ctx.save();
ctx.translate( 0, h * SQ ); // Move the canvas vertically
if( currentSquare === 2) {
ctx.fillStyle = object.fill;
ctx.fillRect( 0, 0, SQ, SQ );
}
else if( typeof currentSquare === 'string' ) {
ctx.fillStyle = currentSquare;
ctx.fillRect( 0, 0, SQ, SQ );
}
ctx.restore();
}
ctx.restore();
}
// draws the grid
for( i = 1; i < WIDTH; i++ )
line( i*SQ, 0, i*SQ, HEIGHT );
for( i = 1; i < HEIGHT; i++ )
line( 0, i*SQ, WIDTH, i*SQ );
}
drawLoop = setInterval(drawMap, 50);
tickLoop = setInterval(tick, 50);
var running = true, drawLoop, tickLoop;
document.onkeydown = function(e) {
var key = e.which;
if( running && key === 38 && canRotate() ) // up - rotate
or = ++or % 4;
else if( key === 40 ) { // down - drop the object by increasing game speed
SPEED = DROPSPEED;
}
else if( key === 83 ) { // s - stop (pause)
if( running ){
clearInterval( drawLoop );
clearInterval( tickLoop );
}
else{
drawLoop = setInterval(drawMap, 50);
tickLoop = setInterval(tick, 50);
}
running = !running;
}
else if( running && key === 37 && canMove(-1) ) // left - move left
hpos--;
else if( running && key === 39 && canMove(1) ) // right - move right
hpos++;
}
document.onkeyup = function(e) { // cancel drop
if( e.which === 40 )
SPEED = ORIGSPEED;
}
}
}
function runBreakout(){
if(GameRunning == false) {
GameRunning = true;
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
var coin;
canvas.width = "600";
canvas.height = "700";
var ballR = 10, x = canvas.width / 2, y = canvas.height - 30,
dx = 4, dy = -4, pongH = 15, pongW = 100, pongX = (canvas.width - pongW) / 2,
rightKey = false, leftKey = false, brickRows = 7, brickCol = 9,
brickW = 75, brickH = 20, brickPadding = 10, brickOffsetTop = 30,
brickOffsetLeft = 8;
var bricks = [];
for (c = 0; c < brickCol; c++) {
for (r = 0; r < brickRows; r++) {
bricks.push({
x : (c * (brickW + brickPadding)) + brickOffsetLeft,
y : (r * (brickH + brickPadding)) + brickOffsetTop,
status : 1
});
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballR, 0, Math.PI * 2);
ctx.fillStyle = "#FFFFF7";
ctx.fill();
ctx.closePath();
}
function drawPong() {
ctx.beginPath();
ctx.rect(pongX, canvas.height - pongH, pongW, pongH);
ctx.fillStyle = "#eeeeee";
ctx.fill();
ctx.closePath();
}
function drawBricks() {
bricks.forEach(function(brick) {
if (!brick.status) return;
ctx.beginPath();
ctx.rect(brick.x, brick.y, brickW, brickH);
ctx.fillStyle = "#EB9532";
ctx.fill();
ctx.closePath();
});
}
function collisionDetection() {
bricks.forEach(function(b) {
if (!b.status) return;
var inBricksColumn = x > b.x && x < b.x + brickW,
inBricksRow = y > b.y && y < b.y + brickH;
if (inBricksColumn && inBricksRow) {
dy = -dy;
coin = Math.floor(Math.random() * 2);
if (coin == 0) {
dy = dy*1.01;
}
if (coin == 1) {
dx = dx*1.01;
}
b.status = 0;
}
});
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBricks();
drawBall();
drawPong();
collisionDetection();
if (hitSideWall()) {
dx = -dx;
coin = Math.floor(Math.random() * 2);
if (coin == 0) {
dx = dx*1.01;
}
if (coin == 1) {
dy = dy*1.01;
}
}
if (hitTop() || hitPong()) {
dy = -dy;
coin = Math.floor(Math.random() * 2);
if (coin == 0) {
dy = dy*1.01;
}
if (coin == 1) {
dx = dx*1.01;
}
}
if (gameOver())
document.location.reload();
var RIGHT_ARROW = 39, LEFT_ARROW = 37;
function hitPong() { return hitBottom() && ballOverPong(); }
function ballOverPong() { return x > pongX && x < pongX + pongW; }
function hitBottom() { return y + dy > canvas.height - ballR; }
function gameOver() { return hitBottom() && !ballOverPong(); }
function hitSideWall() { return x + dx > canvas.width - ballR || x + dx < ballR; }
function hitTop() { return y + dy < ballR; }
function xOutOfBounds() { return x + dx > canvas.width - ballR || x + dx < ballR; }
function rightPressed(e) { return e.keyCode == RIGHT_ARROW; }
function leftPressed(e) { return e.keyCode == LEFT_ARROW; }
function keyDown(e) {
rightKey = rightPressed(e);
leftKey = leftPressed(e);
}
function keyUp(e) {
rightKey = rightPressed(e) ? false : rightKey;
leftKey = leftPressed(e) ? false : leftKey;
}
document.addEventListener("keydown", keyDown, false);
document.addEventListener("keyup", keyUp, false);
var maxX = canvas.width - pongW, minX = 0, pongDelta = rightKey ? 7 : leftKey ? -7 : 0;
pongX = pongX + pongDelta;
pongX = Math.min(pongX, maxX);
pongX = Math.max(pongX, minX);
x += dx;
y += dy;
}
setInterval(draw, 10);
}
}
</script>
</body>
</html>