-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetaballs.py
73 lines (53 loc) · 1.41 KB
/
metaballs.py
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
# Really hokey metaballs implementation. Can't do much on a 5x5 grid.
# https://en.wikipedia.org/wiki/Metaballs
from microbit import *
from math import sqrt, floor
force = 0.005
def get_value(x, y, balls):
value = 0.0
for ball in balls:
position = ball[0]
d = 1.0 / ((x - position[0]) ** 2 + (y - position[1]) ** 2 + 1)
value = value + (d * 3)
return value
def draw(balls):
image = Image(5, 5)
for x in range(5):
for y in range(5):
value = get_value(x, y, balls)
image.set_pixel(x, y, int(floor(value)))
display.show(image)
def delta(position):
if position < 1.0:
return force
elif position > 4.0:
return force * -1
else:
return 0
def update_velocity(velocity, position):
return (
velocity[0] + delta(position[0]),
velocity[1] + delta(position[1])
)
def update_position(position, velocity):
return (
position[0] + velocity[0],
position[1] + velocity[1]
)
def evolve_ball(ball):
position, velocity = ball
velocity = update_velocity(velocity, position)
position = update_position(position, velocity)
return (position, velocity)
def evolve(balls):
return [
evolve_ball(ball)
for ball in balls
]
balls = [
((1.0, 1.1), (0.1, 0.1)),
((3.6, 3.7), (-0.1, -0.05))
]
while(True):
draw(balls)
balls = evolve(balls)