/canvas_life

A component-based Conway's Game of Life.

Primary LanguageJavaScript

Conway’s game of life.

https://pietroiusti.github.io/canvas_life/life.html

The program is built on top of components. No library is used. The way components are structured is based on Eloquent Javascript 3rd Ed. Chapter 19. Components are “objects that are responsible for a piece of the DOM and that thay may contain other components inside them”.

The interface consists in a <canvas> element at the top, and some <button>s and a <select> elements at the bottom (the controls). The user can select the seed of the game or clear the area and paint it her/himself.

The state of the application (consistings in tool, grid, interval, speed) lives in the state variable within the scope of startGridEditor. A component responds to a certain action by updating the central state. When this happens, every component can look at the state and update itself look accordingly. When a component is given a new state, it notifies its child components as well.

Components update the central state (that within the scope of startGridEditor) by dispatching actions, that is, by passing to a managing function the relevant information in the guise of an object. This function creates the new state, and the components have the opportunity of synchronizing themselves with it.

Every component is a class. Their constructor is passed a state and creates a dom property in the istances which points to their corresponding dom element. Each component also has a syncState method, which is used to synchronize it with a new state. Constructors can be passed also values other than the state (one example is the function that the components must use to dispatch a function).

The program starts by calling the startGridEditor function, which creates the “root component” called app, an istance of GridEditor (and appends its dom property to the html page).

The state object is update using the _Object.assign function:

function updateState(state, action) {
  return Object.assign({}, state, action);
}

DOM elements are created using the elt function:

function elt(type, props, ...children) {
  let dom = document.createElement(type);
  if (props) Object.assign(dom, props);
  for (let child of children) {
    if (typeof child != "string") dom.appendChild(child);
    else dom.appendChild(document.createTextNode(child));
  }
  return dom;
}