-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapple.js
50 lines (43 loc) · 871 Bytes
/
apple.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
// Use ES6
"use strict";
const _ = require('lodash');
/*
* Apple class
*/
class Apple {
constructor(options) {
_.assign(this, options);
this.respawn();
}
respawn() {
this.x = Math.random() * this.gridSize | 0;
this.y = Math.random() * this.gridSize | 0;
this._checkCollisions();
return this;
}
_checkCollisions() {
// With snakes
this.snakes.forEach((s) => {
// Head
if(s.x === this.x && s.y === this.y) {
this.respawn();
}
// Tail
s.tail.forEach((t) => {
if(t.x === this.x && t.y === this.y) {
this.respawn();
}
});
});
// With apples
this.apples.forEach((a) => {
// Except self
if(this !== a) {
if(a.x === this.x && a.y === this.y) {
this.respawn();
}
}
});
}
}
module.exports = Apple;