-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.html
101 lines (90 loc) · 3.41 KB
/
snake.html
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
99
100
101
<canvas id="game" width="400" height="400"></canvas>
<script>
class snakeGame {
constructor() {
this.canvas = document.getElementById('game');
this.contex = this.canvas.getContext('2d');
document.addEventListener('keydown', this.onKeyPress.bind(this));
}
init() {
this.posittionX = this.posittionY = 10;
this.appleX = this.appleY = 5;
this.trailSize = 5;
this.trail = [];
this.gridSize = this.tileCount = 20;
this.velocityX = this.velocityY = 0;
this.timer = setInterval(this.loop.bind(this), 1000 / 15);
}
reset() {
clearInterval(this.timer);
this.init()
}
loop() {
this.update();
this.draw();
}
update() {
this.posittionX += this.velocityX;
this.posittionY += this.velocityY;
if (this.posittionX < 0) {
this.posittionX = this.tileCount - 1;
}
if (this.posittionY < 0) {
this.posittionY = this.tileCount - 1;
}
if (this.posittionX > this.tileCount - 1) {
this.posittionX = 0;
}
if (this.posittionY > this.tileCount - 1) {
this.posittionY = 0;
}
this.trail.forEach(t => {
if (this.posittionX === t.posittionX && this.posittionY === t.posittionY) {
this.reset();
}
});
this.trail.push({ posittionX: this.posittionX, posittionY: this.posittionY });
while (this.trail.length > this.trailSize) {
this.trail.shift();
}
if (this.appleX === this.posittionX && this.appleY === this.posittionY) {
this.trailSize++;
this.appleX = Math.floor(Math.random() * this.tileCount);
this.appleY = Math.floor(Math.random() * this.tileCount);
}
}
draw() {
this.contex.fillStyle = 'black';
this.contex.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.contex.fillStyle = 'white';
this.contex.font = '20px Arial';
this.contex.fillText(this.trailSize - 5, 20, 40);
this.contex.fillStyle = 'yellow';
this.trail.forEach(t => {
this.contex.fillRect(t.posittionX * this.gridSize, t.posittionY * this.gridSize, this.gridSize - 5, this.gridSize - 5);
});
this.contex.fillStyle = 'pink';
this.contex.fillRect(this.appleX * this.gridSize, this.appleY * this.gridSize, this.gridSize - 5, this.gridSize - 5);
}
onKeyPress(e) {
if (e.keyCode === 37 && this.velocityX !== 1) {
this.velocityX = -1;
this.velocityY = 0;
}
if (e.keyCode === 38 && this.velocityY !== 1) {
this.velocityX = 0;
this.velocityY = -1;
}
if (e.keyCode === 39 && this.velocityX !== -1) {
this.velocityX = 1;
this.velocityY = 0;
}
if (e.keyCode === 40 && this.velocityY !== -1) {
this.velocityX = 0;
this.velocityY = 1;
}
}
}
const game = new snakeGame();
window.onload = () => game.init();
</script>