if (Math.random() < 0.2) board[i][j] = 1; // 20%的细胞活着
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>生命游戏</title>
<style>
.board {
display: flex;
flex-wrap: wrap;
width: 400px;
height: 400px;
}
.cell {
width: 20px;
height: 20px;
border: 1px solid #333;
.active {
background: #333;
</style>
</head>
<body>
<div class="board"></div>
<script>
// 棋盘宽高
let cols = 20;
let rows = 20;
// 棋盘矩阵
let board = [];
// 棋盘元素
let boardEl = document.querySelector(".board");
// 初始化棋盘
function initBoard() {
for (let i = 0; i < rows; i++) {
board[i] = [];
for (let j = 0; j < cols; j++) {
board[i][j] = 0; // 0表示死细胞,1表示活细胞
let cell = document.createElement("div");
cell.className = "cell";
boardEl.appendChild(cell);
// 随机生成初始活细胞
function randomCells() {