snake
by Normunds Skudra
HTML
<canvas id="snakeGame" width="200" height="200" style="border: 1px solid black;">
</canvas>
JavaScript
var ctx = document.getElementById("snakeGame").getContext("2d");
var snakeGame = {
sartGame: function() {
this.isAlive = true;
this.body.push({x:0, y:1});
this.gameScreen = document.getElementById("snakeGame").getContext("2d");
this.generateFood();
},
isAlive: false,
compareCoords: function(a, b) {
return (a.x == b.x && a.y == b.y);
},
gameScreen: null,
directionDictionery: {
'up': {
x: 0,
y: -1
},
'down': {
x: 0,
y: 1
},
'left': {
x: -1,
y: 0
},
'right': {
x: 1,
y: 0
},
},
translateDirection: function() {
return this.directionDictionery[this.direction];
},
direction: "right",
setDirectionUp: function() {
if (this.direction != "down") {
this.direction = "up";
}
},
setDirectionDown: function() {
if (this.direction != "up") {
this.direction = "down";
}
},
setDirectionLeft: function() {
if (this.direction != "right") {
this.direction = "left";
}
},
setDirectionRight: function() {
if (this.direction != "left") {
this.direction = "right";
}
},
getHeadPosition: function() {
return this.body[0];
},
body: [],
gameGrid: {
x: 20,
y: 20
},
snakeSize: 1,
foodCoords: null,
generateFood: function() {
if (this.gameGrid.x * this.gameGrid.x >= this.snakesize) {
console.log("You won!");
} else {
this.foodCoords = {
x: Math.floor((Math.random() * this.gameGrid.x) + 1),
y: Math.floor((Math.random() * this.gameGrid.y) + 1),
}
this.draw.food(this.foodCoords.x, this.foodCoords.y);
}
},
moveForward: function() {
var next =...