-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
105 lines (95 loc) · 2.8 KB
/
script.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
99
100
101
102
103
104
105
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 800 ;
canvas.height = 600;
let speed = 7; //Set the speed
function drawGame() { //Draw the game
setTimeout(drawGame, 1000/ Speed);
changePlayerPosition();
}
class Sprite { //class to use for the snake and food
constructor({position, velocity}) { //arguement for position of the sprite for the individual ones
this.position = position;
this.velocity = velocity;
this.height = 20;
}
draw(){
ctx.fillStyle = "black"; //set the color of the sprite
ctx.fillRect(this.position.x, this.position.y, 20, this.height); //size the sprite
}
update() {
this.draw()
this.position.y += this.velocity.y;
this.position.x += this.velocity.x;
if (this.position.y + this.height + this.velocity.y >= canvas.height) { //stops sprites from going down off the screen
this.velocity.y = 0; //IF position of sprite it greater than or equal to the height of the canvas, then the velocity will be changed to 0 ayeee loops
console.log(stop)
}
if (this.position.y + this.velocity.y <= 0) { //stops the sprite from going up off the screen
this.velocity.y = 0;
console.log(stop)
}
if (this.position.x + this.velocity.x >= canvas.width) {
this.velocity.x = 0; //IF position of sprite it less than or equal to the width of the canvas, then the velocity will be changed to 0 ayeee loops
console.log(stop)
}
if (this.position.x + this.velocity.x <= 0) { //stops the sprite from going left off the screen
this.velocity.x = 0;
console.log(stop)
}
}
}
class paused {
}
function togglePause(){
if (paused){
paused = true;
}
else if (paused){
paused= false;
}
}
const player = new Sprite({
position: {
x: 400, y: 350 //Snake start position
},
velocity: {
x: 0, y: -1
}
});
const food = new Sprite({
position: {
x: Math.floor(Math.random() * (canvas.width - 20)), //random position for the food
y: Math.floor(Math.random() * (canvas.height - 20))
},
velocity: {
x: 0, y: 0
}
});
function animate() {
window.requestAnimationFrame(animate);
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
player.update();
food.update();
}
animate();
window.addEventListener('keydown', (event) => {
switch (event.key) {
case 'ArrowUp':
player.velocity.y = -1;
break
case 'ArrowDown':
player.velocity.y = 1;
break
case 'ArrowLeft':
player.velocity.x = -1;
break
case 'ArrowRight':
player.velocity.x = 1;
break
case 'p':
togglePause();
break
}
})