1 <!-- A SIMPLE SNAKE GAME MADE BY HTML AND CSS -->
2
3<!DOCTYPE html>
4<html>
5<head>
6 <title></title>
7 <style>
8 html, body {
9 height: 100%;
10 margin: 0;
11 }
12
13 body {
14 background: black;
15 display: flex;
16 align-items: center;
17 justify-content: center;
18 }
19 canvas {
20 border: 1px solid white;
21 }
22 </style>
23</head>
24<body>
25<canvas width="400" height="400" id="game"></canvas>
26<script>
27var canvas = document.getElementById('game');
28var context = canvas.getContext('2d');
29
30var grid = 16;
31var count = 0;
32
33var snake = {
34 x: 160,
35 y: 160,
36
37 // snake velocity. moves one grid length every frame in either the x or y direction
38 dx: grid,
39 dy: 0,
40
41 // keep track of all grids the snake body occupies
42 cells: [],
43
44 // length of the snake. grows when eating an apple
45 maxCells: 4
46};
47var apple = {
48 x: 320,
49 y: 320
50};
51
52// get random whole numbers in a specific range
53// @see https://stackoverflow.com/a/1527820/2124254
54function getRandomInt(min, max) {
55 return Math.floor(Math.random() * (max - min)) + min;
56}
57
58// game loop
59function loop() {
60 requestAnimationFrame(loop);
61
62 // slow game loop to 15 fps instead of 60 (60/15 = 4)
63 if (++count < 4) {
64 return;
65 }
66
67 count = 0;
68 context.clearRect(0,0,canvas.width,canvas.height);
69
70 // move snake by it's velocity
71 snake.x += snake.dx;
72 snake.y += snake.dy;
73
74 // wrap snake position horizontally on edge of screen
75 if (snake.x < 0) {
76 snake.x = canvas.width - grid;
77 }
78 else if (snake.x >= canvas.width) {
79 snake.x = 0;
80 }
81
82 // wrap snake position vertically on edge of screen
83 if (snake.y < 0) {
84 snake.y = canvas.height - grid;
85 }
86 else if (snake.y >= canvas.height) {
87 snake.y = 0;
88 }
89
90 // keep track of where snake has been. front of the array is always the head
91 snake.cells.unshift({x: snake.x, y: snake.y});
92
93 // remove cells as we move away from them
94 if (snake.cells.length > snake.maxCells) {
95 snake.cells.pop();
96 }
97
98 // draw apple
99 context.fillStyle = 'red';
100 context.fillRect(apple.x, apple.y, grid-1, grid-1);
101
102 // draw snake one cell at a time
103 context.fillStyle = 'green';
104 snake.cells.forEach(function(cell, index) {
105
106 // drawing 1 px smaller than the grid creates a grid effect in the snake body so you can see how long it is
107 context.fillRect(cell.x, cell.y, grid-1, grid-1);
108
109 // snake ate apple
110 if (cell.x === apple.x && cell.y === apple.y) {
111 snake.maxCells++;
112
113 // canvas is 400x400 which is 25x25 grids
114 apple.x = getRandomInt(0, 25) * grid;
115 apple.y = getRandomInt(0, 25) * grid;
116 }
117
118 // check collision with all cells after this one (modified bubble sort)
119 for (var i = index + 1; i < snake.cells.length; i++) {
120
121 // snake occupies same space as a body part. reset game
122 if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {
123 snake.x = 160;
124 snake.y = 160;
125 snake.cells = [];
126 snake.maxCells = 4;
127 snake.dx = grid;
128 snake.dy = 0;
129
130 apple.x = getRandomInt(0, 25) * grid;
131 apple.y = getRandomInt(0, 25) * grid;
132 }
133 }
134 });
135}
136
137// listen to keyboard events to move the snake
138document.addEventListener('keydown', function(e) {
139 // prevent snake from backtracking on itself by checking that it's
140 // not already moving on the same axis (pressing left while moving
141 // left won't do anything, and pressing right while moving left
142 // shouldn't let you collide with your own body)
143
144 // left arrow key
145 if (e.which === 37 && snake.dx === 0) {
146 snake.dx = -grid;
147 snake.dy = 0;
148 }
149 // up arrow key
150 else if (e.which === 38 && snake.dy === 0) {
151 snake.dy = -grid;
152 snake.dx = 0;
153 }
154 // right arrow key
155 else if (e.which === 39 && snake.dx === 0) {
156 snake.dx = grid;
157 snake.dy = 0;
158 }
159 // down arrow key
160 else if (e.which === 40 && snake.dy === 0) {
161 snake.dy = grid;
162 snake.dx = 0;
163 }
164});
165
166// start the game
167requestAnimationFrame(loop);
168</script>
169</body>
170</html>
1<html>
2<head>
3<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
4<style>
5canvas {
6 border:1px solid #d3d3d3;
7 background-color: #f1f1f1;
8}
9</style>
10</head>
11<body onload="startGame()">
12<script>
13
14var myGamePiece;
15var myObstacles = [];
16var myScore;
17
18function startGame() {
19 myGamePiece = new component(30, 30, "red", 10, 120);
20 myGamePiece.gravity = 0.05;
21 myScore = new component("30px", "Consolas", "black", 280, 40, "text");
22 myGameArea.start();
23}
24
25var myGameArea = {
26 canvas : document.createElement("canvas"),
27 start : function() {
28 this.canvas.width = 480;
29 this.canvas.height = 270;
30 this.context = this.canvas.getContext("2d");
31 document.body.insertBefore(this.canvas, document.body.childNodes[0]);
32 this.frameNo = 0;
33 this.interval = setInterval(updateGameArea, 20);
34 },
35 clear : function() {
36 this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
37 }
38}
39
40function component(width, height, color, x, y, type) {
41 this.type = type;
42 this.score = 0;
43 this.width = width;
44 this.height = height;
45 this.speedX = 0;
46 this.speedY = 0;
47 this.x = x;
48 this.y = y;
49 this.gravity = 0;
50 this.gravitySpeed = 0;
51 this.update = function() {
52 ctx = myGameArea.context;
53 if (this.type == "text") {
54 ctx.font = this.width + " " + this.height;
55 ctx.fillStyle = color;
56 ctx.fillText(this.text, this.x, this.y);
57 } else {
58 ctx.fillStyle = color;
59 ctx.fillRect(this.x, this.y, this.width, this.height);
60 }
61 }
62 this.newPos = function() {
63 this.gravitySpeed += this.gravity;
64 this.x += this.speedX;
65 this.y += this.speedY + this.gravitySpeed;
66 this.hitBottom();
67 }
68 this.hitBottom = function() {
69 var rockbottom = myGameArea.canvas.height - this.height;
70 if (this.y > rockbottom) {
71 this.y = rockbottom;
72 this.gravitySpeed = 0;
73 }
74 }
75 this.crashWith = function(otherobj) {
76 var myleft = this.x;
77 var myright = this.x + (this.width);
78 var mytop = this.y;
79 var mybottom = this.y + (this.height);
80 var otherleft = otherobj.x;
81 var otherright = otherobj.x + (otherobj.width);
82 var othertop = otherobj.y;
83 var otherbottom = otherobj.y + (otherobj.height);
84 var crash = true;
85 if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
86 crash = false;
87 }
88 return crash;
89 }
90}
91
92function updateGameArea() {
93 var x, height, gap, minHeight, maxHeight, minGap, maxGap;
94 for (i = 0; i < myObstacles.length; i += 1) {
95 if (myGamePiece.crashWith(myObstacles[i])) {
96 return;
97 }
98 }
99 myGameArea.clear();
100 myGameArea.frameNo += 1;
101 if (myGameArea.frameNo == 1 || everyinterval(150)) {
102 x = myGameArea.canvas.width;
103 minHeight = 20;
104 maxHeight = 200;
105 height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
106 minGap = 50;
107 maxGap = 200;
108 gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
109 myObstacles.push(new component(10, height, "green", x, 0));
110 myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
111 }
112 for (i = 0; i < myObstacles.length; i += 1) {
113 myObstacles[i].x += -1;
114 myObstacles[i].update();
115 }
116 myScore.text="SCORE: " + myGameArea.frameNo;
117 myScore.update();
118 myGamePiece.newPos();
119 myGamePiece.update();
120}
121
122function everyinterval(n) {
123 if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
124 return false;
125}
126
127function accelerate(n) {
128 myGamePiece.gravity = n;
129}
130</script>
131<br>
132<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
133<p>Use the ACCELERATE button to stay in the air</p>
134<p>How long can you stay alive?</p>
135</body>
136</html>
1//Javascript game template
2//Move player with arrow keys
3
4var canvas = document.createElement("canvas");
5canvas.width = 500;
6canvas.height = 500;
7document.body.appendChild(canvas);
8var ctx = canvas.getContext("2d");
9
10var player = {x: canvas.width / 2, y: canvas.height / 2, speed: 10};
11var keys = [];
12
13function update() {
14 ctx.clearRect(0, 0, canvas.width, canvas.height);
15
16 ctx.beginPath();
17 ctx.fillStyle = "red";
18 ctx.fillRect(player.x, player.y, 50, 50);
19
20 if (keys[37])
21 player.x -= player.speed;
22 if (keys[38])
23 player.y -= player.speed;
24 if (keys[39])
25 player.x += player.speed;
26 if (keys[40])
27 player.y += player.speed;
28
29 requestAnimationFrame(update);
30}
31update();
32
33document.onkeydown = function(e) {
34 keys[e.keyCode] = true;
35}
36document.onkeyup = function(e) {
37 keys[e.keyCode] = false;
38}