forked from filipporaciti/AppleSnake-p5js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.js
98 lines (71 loc) · 2.15 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class Snake{
constructor(x, y){
this.color = {r:255,g:255,b:255}
this.headColor = {r:50,g:255,b:50}
this.x = x
this.y = y
this.scelta = 'u'
this.bodyRect = [new Rect(this.x, this.y, color=this.color), new Rect(this.x, this.y, color=this.color), new Rect(this.x, this.y, color=this.color)]
this.apple = new Rect(0, 0, {r:255,g:0,b:0})
this.randomApple()
}
show(){
this.apple.show()
controls()
for(let r of this.bodyRect){
r.show()
}
}
randomApple(){
this.apple.x = parseInt(random(canvasWidth/side))*side
this.apple.y = parseInt(random(canvasHeight/side))*side
}
addElement(){
this.bodyRect.push(new Rect(this.x, this.y, color=this.color))
}
moveInterval(){
this.moveRect()
this.gameOver()
this.gameWin()
}
moveRect(){
if(this.scelta == 'u'){
this.y -= side
}
if(this.scelta == 'b'){
this.y += side
}
if(this.scelta == 'l'){
this.x -= side
}
if(this.scelta == 'r'){
this.x += side
}
this.bodyRect[this.bodyRect.length-1].color = this.color
this.bodyRect.push(new Rect(this.x, this.y, this.headColor))
this.bodyRect.shift()
}
move(scelta){
this.scelta = scelta
}
gameWin(){
if(this.x == this.apple.x && this.y == this.apple.y){
this.addElement()
this.randomApple()
score += 10*(this.bodyRect.length-3)
document.getElementById('score').innerHTML = score
}
}
gameOver(){
let collision = false
for(let r of this.bodyRect.slice(0, -1)){
if(this.bodyRect[this.bodyRect.length-1].x == r.x && this.bodyRect[this.bodyRect.length-1].y == r.y){
collision = true
}
}
if(this.x < 0 || this.x > canvasWidth-side || this.y < 0 || this.y > canvasHeight-side || collision){
alert('Game Over')
addClassifica()
}
}
}