-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.js
67 lines (59 loc) · 2.02 KB
/
snake.js
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
const Snake = function(){
this.snakePositions = [ 203, 204, 205, 206 ];
this.tail =this.snakePositions.slice(-1);
this.key = "ArrowRight";
this.foodPosition;
this.sizeOfGrid = 50;
}
Snake.prototype.updateSnakePosToDown = function (ref) {
let tail = ref.snakePositions.shift();
let newSnakeHeadId = ref.snakePositions.slice(-1)[0] + ref.sizeOfGrid;
ref.snakePositions.push(+newSnakeHeadId);
ref.tail = tail;
};
Snake.prototype.updateSnakePosUp = function (ref) {
let tail = ref.snakePositions.shift();
let newSnakeHeadId = ref.snakePositions.slice(-1)[0]-ref.sizeOfGrid;
ref.snakePositions.push(+newSnakeHeadId);
ref.tail = tail;
};
Snake.prototype.updateSnakePosRight = function (ref) {
let tail = ref.snakePositions.shift();
let newSnakeHeadId = ref.snakePositions.slice(-1)[0]+1;
ref.snakePositions.push(+newSnakeHeadId);
ref.tail = tail;
};
Snake.prototype.updateSnakePosLeft = function (ref) {
let tail = ref.snakePositions.shift();
let newSnakeHeadId = ref.snakePositions.slice(-1)[0]-1;
ref.snakePositions.push(+newSnakeHeadId);
ref.tail = tail;
};
Snake.prototype.updateSnakePos = function(key){
let actions ={
"ArrowDown":this.updateSnakePosToDown,
"ArrowRight":this.updateSnakePosRight,
"ArrowUp":this.updateSnakePosUp,
"ArrowLeft":this.updateSnakePosLeft
};
actions[key](this);
}
Snake.prototype.generatedFood = function(){
let maxPossiblePos = this.sizeOfGrid*this.sizeOfGrid;
let foodPosition = Math.floor(Math.random()*maxPossiblePos)
if(this.snakePositions.includes(foodPosition)){
this.generatedFood();
}
this.foodPosition = foodPosition;
}
Snake.prototype.didSnakeEatFood = function(){
let snakeHead = this.snakePositions.slice(-1);
return this.foodPosition == snakeHead;
}
Snake.prototype.isGameOver = function () {
let maxPossiblePos = this.sizeOfGrid*this.sizeOfGrid;
let head = this.snakePositions.slice(-1);
let didSnakeHitTopEdge = head<0;
let didSnakeHitBottomEdge = head>(maxPossiblePos);
return didSnakeHitTopEdge||didSnakeHitBottomEdge
};