-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnake.js
More file actions
68 lines (60 loc) · 1.52 KB
/
Snake.js
File metadata and controls
68 lines (60 loc) · 1.52 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
import { Entity } from "./Entity.js";
export class Snake extends Entity {
lastKeyPress = null;
body = [];
direction = null;
constructor() {
super();
window.addEventListener("keydown", (ev) => {
this.lastKeyPress = ev.key;
});
}
/**
* @param {CanvasRenderingContext2D} ctx
*/
draw(ctx) {
this.handleControls();
this.body[0] = {
x: this.x,
y: this.y,
};
ctx.fillStyle = "#ffff00";
for (let i = 0; i < this.body.length; i++) {
ctx.fillRect(
this.body[i].x,
this.body[i].y,
this.tileSize,
this.tileSize
);
}
}
handleSelfColision() {
if (this.direction === "up" && this.lastKeyPress == "s")
throw new Error("self colision");
if (this.direction === "down" && this.lastKeyPress == "w")
throw new Error("self colision");
if (this.direction === "left" && this.lastKeyPress == "d")
throw new Error("self colision");
if (this.direction === "right" && this.lastKeyPress == "a")
throw new Error("self colision");
}
handleControls() {
// this.handleSelfColision();
if (this.lastKeyPress === "w") {
this.direction = "up";
this.y -= this.tileSize;
}
if (this.lastKeyPress === "s") {
this.direction = "down";
this.y += this.tileSize;
}
if (this.lastKeyPress === "a") {
this.direction = "left";
this.x -= this.tileSize;
}
if (this.lastKeyPress === "d") {
this.direction = "right";
this.x += this.tileSize;
}
}
}