-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple life sim (15).html
98 lines (90 loc) · 2.97 KB
/
simple life sim (15).html
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body, canvas {
margin: 0;
padding: 0;
overflow: hidden;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
<title>Organic Mold Growth Simulation</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const cellSize = 5;
const rows = Math.floor(canvas.height / cellSize);
const cols = Math.floor(canvas.width / cellSize);
function createEmptyGrid() {
return new Array(rows).fill(null).map(() => new Array(cols).fill(0));
}
function placeInitialMold(grid) {
const row = Math.floor(rows / 2);
const col = Math.floor(cols / 2);
grid[row][col] = 1;
}
function countNeighbors(grid, row, col) {
let count = 0;
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
const newRow = Math.max(0, Math.min(rows - 1, row + dx));
const newCol = Math.max(0, Math.min(cols - 1, col + dy));
if (grid[newRow][newCol] === 1) count++;
}
}
return count;
}
function getRandomColor() {
const color = `hsl(${Math.random() * 360}, 100%, ${(Math.random() * 50) + 40}%)`;
return color;
}
function updateGrid(grid) {
const newGrid = grid.map(row => row.slice());
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const neighbors = countNeighbors(grid, row, col);
const randomThreshold = Math.random();
const growth = neighbors * 0.25;
if (neighbors < 2 && grid[row][col] !== 1) {
if (randomThreshold < growth) {
newGrid[row][col] = 1;
}
}
}
}
return newGrid;
}
function drawGrid(grid) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
if (grid[row][col] === 1) {
ctx.fillStyle = getRandomColor();
ctx.beginPath();
ctx.arc(col * cellSize + cellSize / 2, row * cellSize + cellSize / 2, cellSize / 2, 0, Math.PI * 2);
ctx.fill();
}
}
}
}
let grid = createEmptyGrid();
placeInitialMold(grid);
setInterval(() => {
grid = updateGrid(grid);
drawGrid(grid);
}, 200);
</script>
</body>
</html>