SandGame/water.js

120 lines
No EOL
3.9 KiB
JavaScript

import { grid, cols, rows } from './state.js';
import { config } from './config.js';
import { move, swap } from './actions.js';
import { createCell } from './physics.js';
const dxs = [0, 0, -1, 1];
const dys = [1, -1, 0, 0];
export function updateWater(x, y, cell) {
// Thermal & biological reactions
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) {
if (neighbor.type === 'lava') {
// Turn to steam
grid[x][y] = createCell('steam');
grid[nx][ny] = createCell('rock');
return;
} else if ((neighbor.type === 'plant' || neighbor.type === 'grass') && Math.random() < 0.003) {
grid[x][y] = createCell(neighbor.type);
return;
}
}
}
}
// 1. Fall straight down
const below = y + 1;
if (below >= rows) return;
const belowCell = grid[x][below];
if (!belowCell) {
move(x, y, x, below);
return;
}
// Mix and sink through oil (emulsion / separation)
if (belowCell.type === 'oil') {
const sinkChance = config.oil?.sinkChance !== undefined ? config.oil.sinkChance : 0.25;
if (Math.random() < sinkChance) {
swap(x, y, x, below);
return;
}
}
// 2. Diagonal falling
const canDownLeft = x > 0 && (!grid[x - 1][below] || (grid[x - 1][below].type === 'oil' && Math.random() < 0.25));
const canDownRight = x < cols - 1 && (!grid[x + 1][below] || (grid[x + 1][below].type === 'oil' && Math.random() < 0.25));
if (canDownLeft && canDownRight) {
const targetX = Math.random() < 0.5 ? x - 1 : x + 1;
executeWaterStep(x, y, targetX, below);
return;
} else if (canDownLeft) {
executeWaterStep(x, y, x - 1, below);
return;
} else if (canDownRight) {
executeWaterStep(x, y, x + 1, below);
return;
}
// 3. Fast horizontal dispersion (no gel-like stacking)
const flowChance = config.water?.flowChance !== undefined ? config.water.flowChance : 1.0;
if (Math.random() < flowChance) {
const maxDisp = config.water?.dispersion || 5;
const dir = Math.random() < 0.5 ? 1 : -1;
for (const d of [dir, -dir]) {
let targetX = x;
let targetY = y;
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;
// Found an edge or hole? Drop right into it
if (y + 1 < rows && !grid[nx][y + 1]) {
targetX = nx;
break;
}
} else if (c.type === 'oil') {
// Mix sideways with oil
if (Math.random() < 0.3) {
targetX = nx;
}
break;
} else if (c.type === 'water') {
// Fluid surface leveling: if space above is open, can flow across surface
if (y > 0 && !grid[nx][y - 1] && !grid[nx][y]) {
targetX = nx;
} else {
continue;
}
} else {
// Blocked by barrier
break;
}
}
if (targetX !== x) {
executeWaterStep(x, y, targetX, targetY);
return;
}
}
}
}
function executeWaterStep(x1, y1, x2, y2) {
if (grid[x2][y2]) {
swap(x1, y1, x2, y2);
} else {
move(x1, y1, x2, y2);
}
}