about summary refs log tree commit diff stats
path: root/js/sand/sand.js
blob: 65e87bdbcb2c8e09c189aad80f4bf6f6221433f7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const canvas = document.getElementById('sand');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth - 12;
canvas.height = window.innerHeight - 12;

const gridSize = 10;
const gridWidth = Math.floor(canvas.width / gridSize);
const gridHeight = Math.floor(canvas.height / gridSize);
const grid = Array(gridHeight).fill().map(() => Array(gridWidth).fill(0));

let mouseDown = false;

canvas.addEventListener('mousedown', (e) => {
    mouseDown = true;
    addSand(e);
});

canvas.addEventListener('mouseup', () => {
    mouseDown = false;
});

canvas.addEventListener('mousemove', (e) => {
    if (mouseDown) {
        addSand(e);
    }
});

function addSand(e) {
    const rect = canvas.getBoundingClientRect();
    const x = Math.floor((e.clientX - rect.left) / gridSize);
    const y = Math.floor((e.clientY - rect.top) / gridSize);
    if (x >= 0 && x < gridWidth && y >= 0 && y < gridHeight) {
        grid[y][x] = 1;
    }
}

const updateGrid = () => {
    for (let y = gridHeight - 2; y >= 0; y--) {
        for (let x = 0; x < gridWidth; x++) {
            if (grid[y][x] === 1) {
                if (grid[y + 1][x] === 0) {
                    grid[y][x] = 0;
                    grid[y + 1][x] = 1;
                } else if (x > 0 && grid[y + 1][x - 1] === 0) {
                    grid[y][x] = 0;
                    grid[y + 1][x - 1] = 1;
                } else if (x < gridWidth - 1 && grid[y + 1][x + 1] === 0) {
                    grid[y][x] = 0;
                    grid[y + 1][x + 1] = 1;
                }
            }
        }
    }
};

const drawGrid = () => {
    // Clear the canvas
    ctx.fillStyle = 'beige';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // Draw the sand
    ctx.fillStyle = 'black';
    for (let y = 0; y < gridHeight; y++) {
        for (let x = 0; x < gridWidth; x++) {
            if (grid[y][x] === 1) {
                ctx.fillRect(x * gridSize, y * gridSize, gridSize, gridSize);
            }
        }
    }
};

const animate = () => {
    updateGrid();
    drawGrid();
    requestAnimationFrame(animate);
};

animate();