-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.js
More file actions
70 lines (63 loc) · 1.91 KB
/
snake.js
File metadata and controls
70 lines (63 loc) · 1.91 KB
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
export class Snake{
constructor(){
this.direction = 'r'
this.grow = false
this.elements = [
{x: 10, y: 10},
{x: 10, y: 11},
{x: 10, y: 12}
]
}
left = () => {
if(this.direction != 'r'){this.direction = 'l'}
}
right = () => {
if(this.direction != 'l'){this.direction = 'r'}
}
down = () => {
if(this.direction != 'u'){this.direction = 'd'}
}
up = () => {
if(this.direction != 'd'){this.direction = 'u'}
}
update = () => {
if(this.grow){
this.grow = false
this.elements.push({x:this.elements[this.elements.length-1].x, y:this.elements[this.elements.length-1].y})
}
for(let i = this.elements.length - 1; i > 0; i--){
this.elements[i] = {x: this.elements[i - 1].x, y: this.elements[i -1].y}
}
switch(this.direction){
case 'r':
this.elements[0].x += 1
break;
case 'l':
this.elements[0].x -= 1
break
case 'd':
this.elements[0].y += 1
break
case 'u':
this.elements[0].y -= 1
break
}
}
check = (gridSize, food) => {
if(this.elements.slice(1, this.elements.length).some((element) => (this.elements[0].x == element.x && this.elements[0].y == element.y))){
console.log("AteAway")
return true
}else if(
this.elements[0].x < 0 ||
this.elements[0].y < 0 ||
this.elements[0].x >= gridSize.x ||
this.elements[0].y >= gridSize.y){
return true
}
if(food.position.x == this.elements[0].x && food.position.y == this.elements[0].y){
this.grow = true
food.relocate(this.elements)
}
return false
}
}