Published
Edited
Mar 18, 2020
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
mutable balls = {
reset;
return newBalls()
}
Insert cell
newBalls = () => {
let balls = Array.from({length: populationSize}).map(newBall)
if (!balls[0]) return balls;
// infect the first ball
balls[0].state = 'infected'
// freeze the position of roughly nInPlace.
let nInPlace = Math.floor(percentRemainInPlace * balls.length)
for (let i = 1; i <= nInPlace; i++) {
if(!balls[i]) break // so it doesn't break at 100%
balls[i].dx = 0
balls[i].dy = 0
}
return balls;
}
Insert cell
newBall = () => {
const angle = Math.random() * Math.PI
return {
r: 10,
x: Math.random() * w,
y: Math.random() * h,
dx: Math.cos(angle) * speed,
dy: Math.sin(angle) * speed,
state: 'uninfected'
}
}
Insert cell
gameloop = {
i;
let temp = balls.map(moveBall);
//temp = balls.forEach(infectFrom);
mutable balls = temp
yield true;
}
Insert cell
infectFrom = function(ball, i, balls) {
balls.forEach((x) => infect(ball,x))
}
Insert cell
infect = (b1,b2) => {
if (collide(b1,b2) && b1.state == 'infected' && b2.state == 'uninfected') {
b2.state = 'infected'
}
}
Insert cell
moveBall = ball => {
let {r, x, y, dx, dy, state} = ball;
x += dx, y += dy;
//bounce off walls
if (x < r) dx = Math.abs(dx);
if (x + r > w) dx = -Math.abs(dx);
if (y < r) dy = Math.abs(dy);
if (y + r > h) dy = -Math.abs(dy);
const bz = balls
bz.forEach(infectFrom);
ball = {r, x, y, dx, dy, state}
return ball;
}
Insert cell
function collide(b1, b2) {
let dist = Math.sqrt(Math.pow(b1.x - b2.x,2) + Math.pow(b1.y - b2.y,2))
let hit = dist < b1.r + b2.r;
return hit;
}
Insert cell
colors = ({infected:'#f73bb9', uninfected: '#2679b5'})
Insert cell
// currently not using the scrubber value, just ticking when i is updated
viewof i = Scrubber(Array.from({length: 50}, (_, i) => i), {delay:10})
Insert cell
import {Scrubber} from '@mbostock/scrubber'
Insert cell
import {slider, button} from '@jashkenas/inputs'
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more