-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
90 lines (79 loc) · 1.83 KB
/
Copy pathgame.js
File metadata and controls
90 lines (79 loc) · 1.83 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class Item{
shape;
x;
y;
constructor(shape, x, y){
this.shape = shape;
this.x = x;
this.y = y;
this.shape.style.left = x + "px";
this.shape.style.top = y + "px";
}
}
class Food extends Item {
constructor(shape, x, y){
super(shape, x, y)
}
recreate() {
this.x = getRandom20(window.innerWidth - 20)
this.y = getRandom20(window.innerHeight - 20)
this.shape.style.left = this.x + "px";
this.shape.style.top = this.y + "px"
}
}
class Player extends Item {
constructor(shape, x, y){
super(shape, x, y)
}
moveUp() {
this.y -=20;
this.shape.style.top = this.y + "px"
}
moveDown() {
this.y +=20;
this.shape.style.top = this.y + "px"
}
moveLeft() {
this.x -=20;
this.shape.style.left = this.x + "px"
}
moveRight() {
this.x +=20;
this.shape.style.left = this.x + "px"
}
}
function getRandom20(end){
let value = Math.round(Math.random()*end)
return value - (value % 20)
}
let food = new Food(
document.getElementById("food"),
getRandom20(window.innerWidth - 20),
getRandom20(window.innerHeight - 20)
);
let player = new Player(
document.getElementById("player"),
getRandom20(window.innerWidth - 20),
getRandom20(window.innerHeight - 20)
);
window.addEventListener("keydown", e => {
switch (e.keyCode) {
case 38: {
if (player.y > 0) player.moveUp();
break;
}
case 40: {
if (player.y < innerHeight - 20) player.moveDown();
break;
}
case 37: {
if (player.x > 0) player.moveLeft();
break;
}
case 39: {
if (player.x < innerWidth - 20) player.moveRight();
break;
}
}
if (player.x === food.x && player.y === food.y) food.recreate()
})