-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple life sim (16).html
100 lines (90 loc) · 3.11 KB
/
simple life sim (16).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
99
100
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Conway's Game of Life</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id="game" width="1800" height="1800"></canvas>
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const cellSize = 10;
const rows = canvas.height / cellSize;
const cols = canvas.width / cellSize;
function createEmptyBoard() {
return new Array(rows).fill(null).map(() => new Array(cols).fill(false));
}
function randomizeBoard(board) {
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
board[row][col] = Math.random() < 0.5;
}
}
}
function cloneBoard(board) {
return board.map((row) => row.slice(0));
}
function getNeighbors(board, row, col) {
let neighbors = 0;
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
const newRow = (row + dx + rows) % rows;
const newCol = (col + dy + cols) % cols;
if (board[newRow][newCol]) neighbors++;
}
}
return neighbors;
}
function updateBoard(board) {
const newBoard = cloneBoard(board);
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const neighbors = getNeighbors(board, row, col);
if (board[row][col]) {
newBoard[row][col] = neighbors === 2 || neighbors === 3;
} else {
newBoard[row][col] = neighbors === 3;
}
}
}
return newBoard;
}
function drawBoard(board) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
if (board[row][col]) {
ctx.beginPath();
ctx.arc(col * cellSize + cellSize / 2, row * cellSize + cellSize / 2, cellSize / 2, 0, 2 * Math.PI);
ctx.fill();
ctx.beginPath();
ctx.moveTo(col * cellSize, row * cellSize);
ctx.lineTo(col * cellSize + cellSize, row * cellSize + cellSize);
ctx.strokeStyle = 'black';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(col * cellSize + cellSize, row * cellSize);
ctx.lineTo(col * cellSize, row * cellSize + cellSize);
ctx.strokeStyle = 'black';
ctx.stroke();
}
}
}
}
let board = createEmptyBoard();
randomizeBoard(board);
setInterval(() => {
board = updateBoard(board);
drawBoard(board);
}, 100);
</script>
</body>
</html>