<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>康威生命游戏</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
#game-board {
display: inline-block;
border: 1px solid black;
}
.cell {
width: 15px;
height: 15px;
display: inline-block;
background-color: white;
}
.cell.alive {
background-color: black;
}
button {
margin-top: 10px;
}
</style>
</head>
<body>
<h1>康威生命游戏</h1>
<h2 style="font: size 14px;">先点击设定初始图形,再点击开始</h2>
<div id="game-board"></div>
<button onclick="startGame()" style="width: 50px;">开始</button>
<button onclick="clearBoard()" style="width: 50px;">清除</button>
<script>
const ROWS = 30;
const COLS = 60;
let board = [];
let nextBoard = [];
let gameInterval = null;
function initializeBoard() {
board = [];
nextBoard = [];
for (let i = 0; i < ROWS; i++) {
board[i] = [];
nextBoard[i] = [];
for (let j = 0; j < COLS; j++) {
board[i][j] = false;
nextBoard[i][j] = false;
}
}
}
function drawBoard() {
const gameBoard = document.getElementById('game-board');
gameBoard.innerHTML = '';
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
const cell = document.createElement('div');
cell.className = 'cell';
if (board[i][j]) {
cell.classList.add('alive');
}
cell.addEventListener('click', () => {
board[i][j] = !board[i][j];
drawBoard();
});
gameBoard.appendChild(cell);
}
const br = document.createElement('br');
gameBoard.appendChild(br);
}
}
function countNeighbors(row, col) {
let count = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
if (i === 0 && j === 0) {
continue;
}
const neighborRow = row + i;
const neighborCol = col + j;
if (
neighborRow >= 0 &&
neighborRow < ROWS &&
neighborCol >= 0 &&
neighborCol < COLS &&
board[neighborRow][neighborCol]
) {
count++;
}
}
}
return count;
}
function updateBoard() {
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
const neighbors = countNeighbors(i, j);
if (board[i][j]) {
if (neighbors < 2 || neighbors > 3) {
nextBoard[i][j] = false;
} else {
nextBoard[i][j] = true;
}
} else {
if (neighbors === 3) {
nextBoard[i][j] = true;
}
}
}
}
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
board[i][j] = nextBoard[i][j];
}
}
}
function startGame() {
if (gameInterval !== null) {
clearInterval(gameInterval);
gameInterval = null;
}
gameInterval = setInterval(() => {
updateBoard();
drawBoard();
}, 300);
}
function clearBoard() {
if (gameInterval !== null) {
clearInterval(gameInterval);
gameInterval = null;
}
initializeBoard();
drawBoard();
}
initializeBoard();
drawBoard();
</script>
</body>
</html>