Snake
Snake Game
HTML
<!DOCTYPE html>
<body>
<div id="main">
<h1>Snake Game</h1>
<canvas id="ctx" width="500" height="500"></canvas>
<div id="score">SCORE: </div>
<script src="game.js"></script>
</div>
</body>
CSS
html, body, div, canvas {
margin: 0;
padding: 0;
}
body {
background-image: url("img/giftly.png");
background-repeat: repeat;
margin: 6px;
}
#main {
width: 800px;
background-image: url("img/geometry.png");
background-repeat: repeat;
margin: 0px auto;
border-radius: 12px;
padding-bottom: 48px;
box-shadow: 2px 2px 14px #aaa;
}
#main h1 {
text-align: center;
font-size: 58px;
margin: 0px;
padding: 0px;
color: #333;
text-decoration: underline;
}
#ctx {
border: 4px solid #085;
border-radius: 12px;
background-color: #fff;
display: block;
margin-left: auto;
margin-right: auto;
}
#score {
text-align: center;
font-size: 24px;
font-weight: bolder;
font-family: sans-serif;
}
JavaScript
var ctx = document.getElementById("ctx").getContext("2d");
var scoreText = document.getElementById("score");
var entities = [];
var snake = [];
var player;
var score = 0;
var WIDTH = 500;
var HEIGHT = 500;
var gameInterval;
var gameSpeed;
var startingSpeed = 140;
function Entity(x,y) {
this.x = x;
this.y = y;
this.height = 24;
this.width = 24;
this.update = function() {
this.draw();
};
this.draw = function() {
ctx.save();
ctx.fillStyle = this.color;
ctx.fillRect(this.x*25+1,this.y*25+1,this.width,this.height);
ctx.restore();
};
entities[entities.length] = this;
}
function Head(x,y) {
this.x = x;
this.y = y;
this.pressingKey = 0;
this.keyPressed = false;
this.direction = 0;
var superUpdate = this.update;
this.checkCollision = function() {
for(i = 1; i < snake.length; i++) {
if((this.x == snake[i].x) && (this.y == snake[i].y))
restartGame();
}
if((this.x == food.x) && (this.y == food.y)) {
food.randomize();
this.giveBirth();
addScore(10);
}
/*if(this.x<0 || this.x>19 || this.y<0 || this.y>19) {
restartGame();
}*/
}
this.update = function() {
if (this.keyPressed) switch(this.pressingKey) {
case 0:
if (this.direction != 2)
this.direction = 0;
break;
case 1:
if (this.direction != 3)
this.direction = 1;
break;
case 2:
if (this.direction != 0)
this.direction = 2;
break;
case 3:
if (this.direction != 1)
this.direction = 3;
break;
}
switch(this.direction) {
case 0:
this.x++;
...