// Клас для моделювання системи частинок
class ParticleSystem {
constructor(numParticles, canvasWidth, canvasHeight) {
this.particles = [];
this.width = canvasWidth;
this.height = canvasHeight;
// Ініціалізація частинок
for (let i = 0; i < numParticles; i++) {
this.particles.push({
x: Math.random() * canvasWidth,
y: Math.random() * canvasHeight,
vx: (Math.random() - 0.5) * 2,
vy: (Math.random() - 0.5) * 2,
mass: Math.random() * 5 + 1
});
}
}
// Моделювання гравітаційної взаємодії
update(dt = 0.1) {
const G = 0.1; // Гравітаційна константа
// Обчислення сил між частинками
for (let i = 0; i < this.particles.length; i++) {
let fx = 0, fy = 0;
for (let j = 0; j < this.particles.length; j++) {
if (i !== j) {
const dx = this.particles[j].x - this.particles[i].x;
const dy = this.particles[j].y - this.particles[i].y;
const distance = Math.sqrt(dx*dx + dy*dy) + 1; // +1 для уникнення ділення на нуль
const force = G * this.particles[i].mass * this.particles[j].mass / (distance * distance);
fx += force * dx / distance;
fy += force * dy / distance;
}
}
// Оновлення швидкості та позиції
this.particles[i].vx += fx / this.particles[i].mass * dt;
this.particles[i].vy += fy / this.particles[i].mass * dt;
this.particles[i].x += this.particles[i].vx * dt;
this.particles[i].y += this.particles[i].vy * dt;
}
}
}
// Моделювання клітинного автомата (Гра життя)
class GameOfLife {
constructor(width, height) {
this.width = width;
this.height = height;
this.grid = Array(height).fill().map(() => Array(width).fill(0));
this.randomize();
}
randomize() {
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
this.grid[y][x] = Math.random() > 0.7 ? 1 : 0;
}
}
}
step() {
const newGrid = this.grid.map(arr => [...arr]);
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
const neighbors = this.countNeighbors(x, y);
if (this.grid[y][x] === 1) {
newGrid[y][x] = (neighbors === 2 || neighbors === 3) ? 1 : 0;
} else {
newGrid[y][x] = (neighbors === 3) ? 1 : 0;
}
}
}
this.grid = newGrid;
}
countNeighbors(x, y) {
let count = 0;
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (dx === 0 && dy === 0) continue;
const nx = (x + dx + this.width) % this.width;
const ny = (y + dy + this.height) % this.height;
count += this.grid[ny][nx];
}
}
return count;
}
}