<!DOCTYPE html>
<html>
<head>
<title>Randomized Life Game</title>
<style>
table {
border-collapse: collapse;
margin: auto;
}
td {
width: 20px;
height: 20px;
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Randomized Life Game</h1>
<table id="game-board"></table>
<script>
// Create an empty 2D array to represent the game board
const rows = 10;
const columns = 10;
let board = new Array(rows).fill(false).map(() => new Array(columns).fill(false));
// Function to randomize the initial state of the game board
function randomizeBoard() {
for (let i = 0; i < rows; i++) {
for (let j = 0; j < columns; j++) {
board[i][j] = Math.random() < 0.5;
}
}
}
// Function to update the view of the game board
function updateBoardView() {
const gameBoardElement = document.getElementById("game-board");
gameBoardElement.innerHTML = "";
for (let i = 0; i < rows; i++) {
const rowElement = document.createElement("tr");
for (let j = 0; j < columns; j++) {
const cellElement = document.createElement("td");
cellElement.style.backgroundColor = board[i][j] ? "black" : "white";
rowElement.appendChild(cellElement);
}
gameBoardElement.appendChild(rowElement);
}
}
// Function to apply game rules and update the game board state
function updateBoardState() {
const newBoard = new Array(rows).fill(false).map(() => new Array(columns).fill(false));
for (let i = 0; i < rows; i++) {
for (let j = 0; j < columns; j++) {
const aliveNeighbors = countAliveNeighbors(i, j);
if (board[i][j]) {
if (aliveNeighbors === 2 || aliveNeighbors === 3) {
newBoard[i][j] = true;
}
} else {
if (aliveNeighbors === 3) {
newBoard[i][j] = true;
}
}
}
}
board = newBoard;
}
// Function to count the number of alive neighbors of a cell
function countAliveNeighbors(row, column) {
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 + rows) % rows;
const neighborColumn = (column + j + columns) % columns;
if (board[neighborRow][neighborColumn]) {
count++;
}
}
}
return count;
}
// Function to start the game loop
function startGame() {
randomizeBoard();
updateBoardView();
setInterval(() => {
updateBoardState();
updateBoardView();
}, 1000); // Update every 1 second
}
// Start the game
startGame();
</script>
</body>
</html>
ジョーク:ライフゲームは、実際の人生から逃げるための最適な方法です!