JavaScript implementation of the Game of Life

JavaScript implementation of the Game of Life

Concept Introduction

Cellular Automata was proposed by John von Neumann, the father of computer, in the early 1950s in order to simulate the self-replication function of living systems.

The Game of Life, or its full name John Conway's Game of Life, is a cellular automaton invented by British mathematician John Conway in the 1970s.

Logical rules

In a two-dimensional plane grid, each cell has two states: alive or dead, and its state at the next moment is completely determined by the states of the eight cells around it.

There are three evolutionary rules in this world:

  1. When there are 2 surviving cells around, the life state of the cell remains the same;
  2. When there are 3 living cells around, the cell is alive (dead cells will be resurrected);
  3. When there are less than 2 surviving cells around (low life count) or more than 3 surviving cells around (too many life counts), the cell is dead.

Complete code

Burning Frost/LifeGame

Demo Page

Basic structure

index.html // Main page, initialize the system, control system operation, etc. canvas.js // Rendering layer, create canvas, manually draw, canvas update method, etc. LifeGame.js // Logic layer, create and run system, system operation logic, data update, etc.

Main Implementation

System configuration: defines the size of the two-dimensional plane grid. The life status of all cells is stored in the data in the form of key and value. Execute is an internal method exposed by canvas.js and mounted on the config object.

  const config = {
    width: 100, // horizontal cell number height: 100, // vertical cell number size: 4 + 1, // cell size, cell spacing 1px
    speed: 200, // cell iteration speed alive: '#000000', // cell survival color dead: '#FFFFFF', // world color (cell death color)
    data: new Map(), // System operation data execute, // Update canvas method};

Rule implementation: traverse each cell in the two-dimensional plane, get the current cell state, calculate the number of surviving cells around it, determine whether it will be alive or dead at the next moment, save this state, and update the interface display by calling the update canvas method execute of the rendering layer. Here, when processing data, a two-dimensional array is not used to represent the two-dimensional coordinate system. Instead, it is converted into a one-dimensional linear representation and the data is stored in a Map.

  // LifeGame.js

  // One-dimensional linear representation of a two-dimensional coordinate system const MakeKey = (x = 0, y = 0) => y * 10000 + x;

  function refreshWorld() {
    const next = new Map(); // Updated system operation data // Iterate all elements of the two-dimensional coordinate system IterateCells(config, (x, y) => {
      const index = MakeKey(x, y); // Calculate the key corresponding to the coordinate
      const current = config.data.get(index); // Current cell state // Calculate the number of surviving cells around the current cell switch (borderSum(x, y)) {
        case 2:
          // When there are 2 live cells around, the cell remains as is.
          next.set(index, current);
          break;
        case 3:
          // When there are 3 surviving cells around it, the cell is alive.
          next.set(index, true);
          !current && config.execute(x, y, true); // Status changes, update canvas break;
        default:
          // When the number of living cells around it is less than 2, the cell is dead. (Life is scarce)
          // When there are more than 3 living cells around, the cell is dead. (Too many lives)
          next.set(index, false);
          current && config.execute(x, y, false); // Status changes, update canvas break;
      }
      return true;
    });
    return next;
  }

Starting and stopping the system

  // LifeGame.js
  
  // Start the system function startWorld() {
    stopWorld(); // Stop the previously started loop // Start the system according to the iteration speed and update the system in a loop interval = setInterval(() => (config.data = refreshWorld()), config.speed || 500);
    starting = true; // Turn on the startup flag return true;
  }

  // Shut down the system, and keep the current system running data function stopWorld() {
    clearInterval(interval); // Stop the loop starting = false; // Turn off the start flag return true;
  }

Methods for counting viable cells

  // LifeGame.js
  
  function borderSum(x = 0, y = 0) {
    const { width, height, data } = config;
    let sum = 0;
    for (let j = y - 1; j <= y + 1; j++) {
      for (let i = x - 1; i <= x + 1; i++) {
        // Boundary judgment if (i < 0 || j < 0 || i >= width || j >= height || (i === x && j === y)) {
          continue;
        }
        if (data.get(MakeKey(i, j))) {
          sum++; // Accumulate the number of surviving cells}
      }
    }
    return sum;
  }

Iterative 2D Coordinate Method

/**
 * Iterate all elements of the 2D coordinate system and execute the callback function* @param config: { width: number, height: number }
 * @param callback: (x: number, y: number) => boolean
 */
const IterateCells = ({ width, height }, callback) => {
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      if (callback && !callback(x, y)) {
        return false;
      }
    }
  }
  return true;
};

Update canvas method

  // canvas.js
  
  function execute(x, y, life) {
    const { size, alive, dead } = config;
    // Set cell color context.fillStyle = life ? alive : dead;
    // Draw cells with a spacing of 1px between cells
    context.fillRect(x * size + 1, y * size + 1, size - 1, size - 1);

    return true;
  }

The above is the details of JavaScript's implementation of the Game of Life. For more information about JavaScript's Game of Life, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Native JS to implement click number game
  • Implementing a puzzle game with js
  • js to implement the snake game with comments
  • Native js to implement 2048 game
  • JavaScript typing game
  • JavaScript jigsaw puzzle game
  • Native js implements a minesweeper game with custom difficulty
  • js canvas to realize the Gobang game
  • How to use JavaScript to write a fighting game
  • Implementing a simple minesweeper game based on JavaScript

<<:  MySQL database design: detailed explanation of Schema operation method using Python

>>:  Comparative Analysis of High Availability Solutions of Oracle and MySQL

Recommend

Implementation example of JS native double-column shuttle selection box

Table of contents When to use Structural branches...

A few things you need to know about responsive layout

1. Introduction Responsive Web design allows a we...

MySQL isolation level detailed explanation and examples

Table of contents 4 isolation levels of MySQL Cre...

CentOS6 upgrade glibc operation steps

Table of contents background Compile glibc 2.14 M...

Detailed explanation of keepAlive use cases in Vue

In development, it is often necessary to cache th...

Detailed explanation of Linux server status and performance related commands

Server Status Analysis View Linux server CPU deta...

TimePicker in element disables part of the time (disabled to minutes)

The project requirements are: select date and tim...

Vue implements user login and token verification

In the case of complete separation of the front-e...

How to install binary MySQL on Linux and crack MySQL password

1. Make sure the system has the required libaio s...

Example of how to implement value transfer between WeChat mini program pages

Passing values ​​between mini program pages Good ...

Detailed explanation of several solutions for JavaScript interruption requests

Table of contents 1 Promise Interrupt the call ch...

Detailed explanation of Linux rpm and yum commands and usage

RPM package management A packaging and installati...

Detailed process of deploying Docker to WSL2 in IDEA

The local environment is Windows 10 + WSL2 (Ubunt...