-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.ts
68 lines (58 loc) · 1.71 KB
/
snake.ts
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
class Snake {
body: number[][];
course: string;
courseflag: boolean;
alive: boolean;
matrix: Matrix;
constructor(matrix: Matrix, row: number, col: number, course: string){
this.body = [[row, col]];
this.course = course;
this.courseflag = true;
this.alive = true;
this.matrix = matrix;
}
create() {
this.matrix.setCell(this.body[0][0], this.body[0][1], true, 'snake');
}
checkAlive() {
var maxrows:number = this.matrix.rows;
var maxcols:number = this.matrix.cols;
if(this.body.length > 3){
this.alive = !this.body.some(function(currentItem, index: number){
if(index > 0)
return (this.body[0][0] == currentItem[0] && this.body[0][1] == currentItem[1])
}, this);
}
if(this.body[0][0] < 1 || this.body[0][1] < 1 ||
this.body[0][0] > maxcols || this.body[0][1] > maxrows)
this.alive = false;
};
move() {
this.courseflag = true;
var last_body = this.body.slice();
switch(this.course)
{
case 'right':
this.body.unshift([this.body[0][0], this.body[0][1] + 1]);
break;
case 'left':
this.body.unshift([this.body[0][0], this.body[0][1] - 1]);
break;
case 'up':
this.body.unshift([this.body[0][0] - 1 , this.body[0][1]]);
break;
case 'down':
this.body.unshift([this.body[0][0] + 1 , this.body[0][1]]);
break;
}
this.body.pop();
this.checkAlive();
if(this.alive){
this.matrix.setCell(last_body[last_body.length - 1][0], last_body[last_body.length - 1][1], false, 'snake');
this.matrix.setCell(this.body[0][0], this.body[0][1], true, 'snake');}
}
eat(){
this.body.push(this.body[this.body.length - 1]);
this.matrix.setCell(this.body[this.body.length - 1][0], this.body[this.body.length - 1][1], true, 'snake');
};
};