-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
117 lines (107 loc) · 2.56 KB
/
game.js
File metadata and controls
117 lines (107 loc) · 2.56 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// import { setupListener } from "./tools/tools.js";
import { } from "./tools/onmove.js";
import { enqueue } from "./tools/animation.js";
function speed() {
let result = 0;
while (result == 0)
result = (Math.random() - 0.5) * 128;
return result;
}
class Star {
x;
y;
dx;
dy;
gx=0;
gy=0;
radius;
constructor(x, y, dx, dy) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = 3;
}
update(elapsedTime) {
this.x += this.dx * elapsedTime / 1000;
this.y += this.dy * elapsedTime / 1000;
}
valid(x1, y1, x2, y2) {
return this.x >= x1 && this.x <= x2 && this.y >= y1 && this.y <= y2;
}
/**
*
* @param {CanvasRenderingContext2D} context
*/
draw(context) {
context.beginPath();
context.ellipse(this.x, this.y, this.radius, this.radius, 0, 0, Math.PI * 2);
context.stroke();
}
}
class Game {
/**
* @type {HTMLCanvasElement}
*/
canvas;
/**
* @type {CanvasRenderingContext2D}
*/
context;
/**
* @type {Set.<Star>}
*/
stars;
// /**
// *
// * @param {Map.<String,Object>} others
// */
// others;
constructor(canvas, context) {
this.canvas = canvas;
this.context = context;
this.stars = new Set();
// this.others = others;
}
start() {
enqueue(this.random.bind(this));
enqueue(this.update.bind(this));
}
random() {
if (Math.random() > 0.4) return;
let dx = speed();
let dy = speed();
// let x = window.screenLeft;
// let y = window.screenTop;
// let gx = 0;
// let gy = 0;
// let c = 0;
// this.others.forEach((value, key) => {
// c++;
// gx += x - value.x;
// gy += y - value.y;
// })
// if (c > 0) {
// gx = gx / c;
// gy = gy / c;
// dx -= gx / 3;
// dy -= gy / 3;
// }
dx-=this.gx/3;
dy-=this.gy/3;
let star = new Star(this.canvas.width / 2, this.canvas.height / 2, dx, dy);
this.stars.add(star);
}
update(elapsedTime) {
this.context.reset();
this.stars.forEach(star => {
star.update(elapsedTime);
if (star.valid(0, 0, this.canvas.width, this.canvas.height)) {
star.draw(this.context);
} else {
this.stars.delete(star);
}
})
}
}
export { Game };