Here's a complete falling sand simulation in a single HTML file:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Falling Sand Simulation</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #222;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
font-family: Arial, sans-serif;
}
#container {
text-align: center;
}
canvas {
border: 2px solid #444;
cursor: crosshair;
display: block;
margin: 0 auto;
}
#controls {
margin-top: 20px;
color: #fff;
}
button {
margin: 0 5px;
padding: 10px 20px;
font-size: 16px;
background-color: #444;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #555;
}
button.active {
background-color: #666;
}
#info {
margin-top: 10px;
color: #aaa;
font-size: 14px;
}
</style>
</head>
<body>
<div id="container">
<canvas id="canvas"></canvas>
<div id="controls">
<button id="sandBtn" class="active">Sand</button>
<button id="waterBtn">Water</button>
<button id="stoneBtn">Stone</button>
<button id="clearBtn">Clear</button>
</div>
<div id="info">
Click and drag to place particles. Use buttons to switch materials.
</div>
</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Canvas setup
const CELL_SIZE = 2;
const WIDTH = 400;
const HEIGHT = 300;
const COLS = WIDTH / CELL_SIZE;
const ROWS = HEIGHT / CELL_SIZE;
canvas.width = WIDTH;
canvas.height = HEIGHT;
// Particle types
const EMPTY = 0;
const SAND = 1;
const WATER = 2;
const STONE = 3;
// Colors
const colors = {
[EMPTY]: '#000000',
[SAND]: '#f4d03f',
[WATER]: '#3498db',
[STONE]: '#7f8c8d'
};
// Grid initialization
let grid = Array(ROWS).fill().map(() => Array(COLS).fill(EMPTY));
let nextGrid = Array(ROWS).fill().map(() => Array(COLS).fill(EMPTY));
// Mouse state
let mouseDown = false;
let currentMaterial = SAND;
// Helper functions
function isInBounds(row, col) {
return row >= 0 && row < ROWS && col >= 0 && col < COLS;
}
function isEmpty(row, col) {
return isInBounds(row, col) && grid[row][col] === EMPTY;
}
function swap(r1, c1, r2, c2) {
const temp = nextGrid[r1][c1];
nextGrid[r1][c1] = nextGrid[r2][c2];
nextGrid[r2][c2] = temp;
}
// Update functions for different materials
function updateSand(row, col) {
// Try to fall straight down
if (isEmpty(row + 1, col)) {
swap(row, col, row + 1, col);
}
// Try to fall diagonally
else if (isEmpty(row + 1, col - 1) && isEmpty(row + 1, col + 1)) {
// Random choice between left and right
if (Math.random() < 0.5) {
swap(row, col, row + 1, col - 1);
} else {
swap(row, col, row + 1, col + 1);
}
}
else if (isEmpty(row + 1, col - 1)) {
swap(row, col, row + 1, col - 1);
}
else if (isEmpty(row + 1, col + 1)) {
swap(row, col, row + 1, col + 1);
}
}
function updateWater(row, col) {
// Try to fall straight down
if (isEmpty(row + 1, col)) {
swap(row, col, row + 1, col);
}
// Try to fall diagonally
else if (isEmpty(row + 1, col - 1) && isEmpty(row + 1, col + 1)) {
if (Math.random() < 0.5) {
swap(row, col, row + 1, col - 1);
} else {
swap(row, col, row + 1, col + 1);
}
}
else if (isEmpty(row + 1, col - 1)) {
swap(row, col, row + 1, col - 1);
}
else if (isEmpty(row + 1, col + 1)) {
swap(row, col, row + 1, col + 1);
}
// Try to move horizontally
else if (isEmpty(row, col - 1) && isEmpty(row, col + 1)) {
if (Math.random() < 0.5) {
swap(row, col, row, col - 1);
} else {
swap(row, col, row, col + 1);
}
}
else if (isEmpty(row, col - 1)) {
swap(row, col, row, col - 1);
}
else if (isEmpty(row, col + 1)) {
swap(row, col, row, col + 1);
}
}
// Main update loop
function update() {
// Copy current grid to next grid
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
nextGrid[row][col] = grid[row][col];
}
}
// Update particles from bottom to top
for (let row = ROWS - 1; row >= 0; row--) {
for (let col = 0; col < COLS; col++) {
const particle = grid[row][col];
if (particle === SAND) {
updateSand(row, col);
} else if (particle === WATER) {
updateWater(row, col);
}
// Stone doesn't move
}
}
// Swap grids
[grid, nextGrid] = [nextGrid, grid];
}
// Rendering
function render() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const particle = grid[row][col];
if (particle !== EMPTY) {
ctx.fillStyle = colors[particle];
ctx.fillRect(col * CELL_SIZE, row * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
}
}
// Mouse event handlers
function getMousePos(e) {
const rect = canvas.getBoundingClientRect();
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
}
function placeMaterial(x, y) {
const col = Math.floor(x / CELL_SIZE);
const row = Math.floor(y / CELL_SIZE);
// Place in a small area for better effect
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
const r = row + dr;
const c = col + dc;
if (isInBounds(r, c) && grid[r][c] === EMPTY) {
grid[r][c] = currentMaterial;
}
}
}
}
canvas.addEventListener('mousedown', (e) => {
mouseDown = true;
const pos = getMousePos(e);
placeMaterial(pos.x, pos.y);
});
canvas.addEventListener('mousemove', (e) => {
if (mouseDown) {
const pos = getMousePos(e);
placeMaterial(pos.x, pos.y);
}
});
canvas.addEventListener('mouseup', () => {
mouseDown = false;
});
canvas.addEventListener('mouseleave', () => {
mouseDown = false;
});
// Button event handlers
document.getElementById('sandBtn').addEventListener('click', function() {
currentMaterial = SAND;
updateActiveButton(this);
});
document.getElementById('waterBtn').addEventListener('click', function() {
currentMaterial = WATER;
updateActiveButton(this);
});
document.getElementById('stoneBtn').addEventListener('click', function() {
currentMaterial = STONE;
updateActiveButton(this);
});
document.getElementById('clearBtn').addEventListener('click', () => {
grid = Array(ROWS).fill().map(() => Array(COLS).fill(EMPTY));
});
function updateActiveButton(activeBtn) {
document.querySelectorAll('button').forEach(btn => {
btn.classList.remove('active');
});
activeBtn.classList.add('active');
}
// Animation loop
function animate() {
update();
render();
requestAnimationFrame(animate);
}
// Start the simulation
animate();
</script>
</body>
</html>
This falling sand simulation includes:
Sand particles that fall down and pile up realistically
Water particles that flow and spread horizontally
Stone particles that stay fixed in place
Click and drag functionality to place particles
Material selection buttons
A clear button to reset the canvas
The simulation uses a cellular automaton approach where each particle follows simple rules based on its type. Sand falls straight down or diagonally, water flows more freely including horizontal movement, and stone remains stationary. The particles interact naturally with each other, creating realistic piling and flowing effects.