-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlife.html
117 lines (89 loc) · 3.19 KB
/
life.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<canvas id="life" width="1900" height="950"></canvas>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<button id="play">Play Song ►</button>
<button id="stop">Stop Song ▋</button>
<script>
m=document.getElementById("life").getContext("2d")
let play = document.getElementById("play")
function playMusic(){
let music = new Audio("Life.mp3")
music.play()
}
play.addEventListener("click",playMusic)
draw=(x,y,c,s)=>{
m.fillStyle=c
m.fillRect(x,y,s,s)
}
particles=[]
particle=(x,y,c)=>{
return{"x":x, "y":y, "vx":0, "vy":0, "color":c}
}
random=()=>{
return Math.random()*400+50
}
create=(number, color)=>{
group=[]
for(let i=0; i< number; i++){
group.push(particle(random(), random(),color))
particles.push(group[i])
}
return group
}
rule=(particles1, particles2, g)=>{
for(let i=0; i < particles1.length; i++){
fx = 0
fy = 0
for(let j=0; j < particles2.length; j++){
a= particles1[i]
b= particles2[j]
dx= a.x-b.x
dy= a.y-b.y
d= Math.sqrt(dx*dx+dy*dy)
if(d > 0 && d < 80){
F = g* 1/d
fx += (F*dx)
fy += (F*dy)
}
}
a.vx = (a.vx + fx) * 0.5
a.vy = (a.vy + fy) * 0.5
a.x += a.vx
a.y += a.vy
if(a.x <= 0 || a.x >= 500){
a.vx *= -1
}
if(a.y <= 0 || a.y >= 500){
a.vy *= -1
}
}
}
yellow= create(400,"yellow")
red = create(400,"red")
green = create(400,"green")
blue = create(400,"blue")
white = create(400,"white")
purple = create(400,"purple")
update=()=>{
rule(red, yellow, -8)
rule(white, blue, 8)
rule(blue, white, -8)
rule(blue, purple, 8)
rule(yellow, red, 8)
rule(green, yellow, 8)
rule(yellow, green, -8)
rule(purple, blue, -8)
rule(red, green, 8)
rule(green, red, -8)
rule(purple, white, 8)
rule(white, purple, -8)
m.clearRect(0,0,500,500)
draw(0,0,"black", 1960)
for(i=0; i<particles.length; i++){
draw(particles[i].x, particles[i].y,particles[i].color,3)
}
requestAnimationFrame(update)
}
update();
</script>
</body>