SandGame/oil.js

106 lines
3.3 KiB
JavaScript
Raw Permalink Normal View History

import { grid, cols, rows } from './state.js';
import { config } from './config.js';
import { move, swap } from './actions.js';
import { createCell } from './physics.js';
export function updateOil(x, y, cell) {
// 1. Ignition from heat/fire/lava
const dxs = [0, 0, -1, 1];
const dys = [-1, 1, 0, 0];
for (let i = 0; i < 4; i++) {
const nx = x + dxs[i];
const ny = y + dys[i];
if (nx >= 0 && nx < cols && ny >= 0 && ny < rows) {
const neighbor = grid[nx][ny];
if (neighbor && (neighbor.type === 'fire' || neighbor.type === 'lava')) {
grid[x][y] = createCell('fire');
if (y > 0 && !grid[x][y - 1]) {
grid[x][y - 1] = createCell('smoke');
}
return;
}
}
}
// 2. Oil buoyancy: oil floats up through water over time (emulsion separation)
if (y > 0 && grid[x][y - 1] && grid[x][y - 1].type === 'water') {
const floatChance = config.oil?.floatChance !== undefined ? config.oil.floatChance : 0.25;
if (Math.random() < floatChance) {
swap(x, y, x, y - 1);
return;
}
}
// 3. Straight fall
const below = y + 1;
if (below >= rows) return;
const belowCell = grid[x][below];
if (!belowCell) {
move(x, y, x, below);
return;
}
// 4. Diagonal fall
const canDownLeft = x > 0 && (!grid[x - 1][below] || (grid[x - 1][below].type === 'water' && Math.random() < 0.25));
const canDownRight = x < cols - 1 && (!grid[x + 1][below] || (grid[x + 1][below].type === 'water' && Math.random() < 0.25));
if (canDownLeft && canDownRight) {
const targetX = Math.random() < 0.5 ? x - 1 : x + 1;
executeOilStep(x, y, targetX, below);
return;
} else if (canDownLeft) {
executeOilStep(x, y, x - 1, below);
return;
} else if (canDownRight) {
executeOilStep(x, y, x + 1, below);
return;
}
// 5. Fast horizontal fluid flow
const flowChance = config.oil?.flowChance !== undefined ? config.oil.flowChance : 0.85;
if (Math.random() < flowChance) {
const maxDisp = config.oil?.dispersion || 4;
const dir = Math.random() < 0.5 ? 1 : -1;
for (const d of [dir, -dir]) {
let targetX = x;
for (let step = 1; step <= maxDisp; step++) {
const nx = x + d * step;
if (nx < 0 || nx >= cols) break;
const c = grid[nx][y];
if (!c) {
targetX = nx;
if (y + 1 < rows && !grid[nx][y + 1]) {
targetX = nx;
break;
}
} else if (c.type === 'water') {
// Mix sideways with water
if (Math.random() < 0.3) {
targetX = nx;
}
break;
} else {
break;
}
}
if (targetX !== x) {
executeOilStep(x, y, targetX, y);
return;
}
}
}
}
function executeOilStep(x1, y1, x2, y2) {
if (grid[x2][y2]) {
swap(x1, y1, x2, y2);
} else {
move(x1, y1, x2, y2);
}
}