-
Notifications
You must be signed in to change notification settings - Fork 0
/
board.js
79 lines (56 loc) · 1.7 KB
/
board.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
68
69
70
71
72
73
74
75
76
77
78
79
(function(root){
var SnakeGame = root.SnakeGame = (root.SnakeGame || {});
var Board = SnakeGame.Board = function(size){
this.grid = this.makeGrid(size);
this.snake = new SnakeGame.Snake();
this.setSnake();
this.mouse = this.spawnMouse();
this.score = 0;
}
Board.prototype.setSnake = function(){
var that = this;
this.snake.segments.forEach(function(seg){
that.grid[seg.pos[1]][seg.pos[0]] = 'S';
})
}
Board.prototype.spawnMouse = function(){
var mouse = new SnakeGame.Mouse(this.grid.length);
while(this.grid[mouse.pos[1]][mouse.pos[0]] === "S"){
mouse.pos = mouse.randomPos(this.grid.length);
}
this.grid[mouse.pos[1]][mouse.pos[0]] = 'M';
return mouse;
}
Board.prototype.render = function() {
$('#score').html('Score: ' + this.score);
this.grid.forEach(function(row) {
console.log(row);
})
}
Board.prototype.update = function(){
var lastPos = _.last(this.snake.segments).pos;
this.grid[lastPos[1]][lastPos[0]] = '.';
this.snake.move();
this.snake.offScreen(this.grid.length)
var firstPos = _.first(this.snake.segments).pos;
if (this.snake.checkCollision(firstPos))
return false;
if (firstPos[0] == this.mouse.pos[0] && firstPos[1] == this.mouse.pos[1]){
this.snake.grow(lastPos);
this.mouse = this.spawnMouse();
this.score += 1;
$('#score').html('Score: ' + this.score);
}
this.grid[firstPos[1]][firstPos[0]] = 'S';
}
Board.prototype.makeGrid = function(size) {
grid = []
for(var i = 0; i < size; i++) {
grid.push([]);
for(var j = 0; j < size; j++) {
grid[i].push(".");
}
}
return grid;
}
})(this)