css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <canvas id="myCanvas" width="400" height="400"></canvas>
            
          
!
            
              const MergeLifeRender = function () {
  this.parseUpdateRule = function (hexCode) {
    const i = hexCode.indexOf(';')
    if (i !== -1) {
      hexCode = hexCode.substring(0, i)
    }
    hexCode = hexCode.replace(/\W+/g, '')
    const result = []
    for (let i = 0; i < 8; i++) {
      const i2 = i * 4
      const o1 = hexCode.substr(i2, 2)
      const o2 = hexCode.substr(i2 + 2, 2)
      const o1d = parseInt(o1, 16)
      let o2d = parseInt(o2, 16)
      if ((o2d & 0x80) > 0) {
        o2d = o2d - 0x100
      }

      const percent = (o2d > 0) ? o2d / 127.0 : o2d / 128.0

      let range = o1d * 8
      if (range >= 2040) {
        range = 2048
      }

      result.push([range, percent, i, o1, o2, o1d, o2d])
    }

    result.sort(function (a, b) {
      return a[0] - b[0]
    })
    return result
  }

  this.randomGrid = function (grid) {
    const grid2 = grid || this.grid[this.currentGrid]
    for (let row = 0; row < grid2.length; row += 1) {
      const line = grid2[row]
      for (let col = 0; col < line.length; col += 1) {
        const pixel = line[col]
        for (let i = 0; i < 3; i++) {
          pixel[i] = Math.floor(Math.random() * 256)
        }
      }
    }
  }

  this.calculateModeGrid = function (gridIn, gridOut) {
    const freq = Array.apply(null, Array(256)).map(Number.prototype.valueOf, 0)

    for (let row = 0; row < gridIn.length; row += 1) {
      const lineIn = gridIn[row]
      const lineOut = gridOut[row]
      for (let col = 0; col < lineIn.length; col += 1) {
        const pixel = lineIn[col]
        let sum = 0
        for (let i = 0; i < 3; i++) {
          sum += pixel[i]
        }
        const v = Math.floor(sum / 3)
        freq[v] += 1
        lineOut[col] = v
      }
    }

    return freq.indexOf(Math.max(...freq))
  }

  this.sumNeighbor = function (grid, row, col, pad) {
    const colTransform = [0, 0, -1, 1, -1, 1, 1, -1]
    const rowTransform = [-1, 1, 0, 0, -1, 1, -1, 1]

    let sum = 0
    for (let i = 0; i < colTransform.length; i++) {
      const neighborRow = rowTransform[i] + row
      const neighborCol = colTransform[i] + col
      if (neighborRow >= 0 && neighborCol >= 0 && neighborRow < grid.length && neighborCol < grid[0].length) {
        sum += grid[neighborRow][neighborCol]
      } else {
        sum += pad
      }
    }
    return sum
  }

  this.updateStep = function (grid, gridNext, updateRule) {
    this.gridMode = this.calculateModeGrid(grid, this.mergeGrid)

    for (let row = 0; row < grid.length; row += 1) {
      const line = grid[row]
      const lineNext = gridNext[row]
      for (let col = 0; col < line.length; col += 1) {
        const nc = this.sumNeighbor(this.mergeGrid, row, col, this.gridMode)

        for (let i = 0; i < updateRule.length; i++) {
          if (nc < updateRule[i][0]) {
            let ki = updateRule[i][2]
            let pct = updateRule[i][1]

            if (pct < 0) {
              pct = Math.abs(pct)
              ki += 1
              if (ki >= updateRule.length) {
                ki = 0
              }
            }

            for (let j = 0; j < 3; j++) {
              let d = MergeLifeRender.prototype.KEY_COLOR[ki][j] - grid[row][col][j]
              d *= pct
              d = Math.floor(d)
              lineNext[col][j] = line[col][j] + d
            }
            break
          }
        }
      }
    }
  }

  this.getColor = function (pixel) {
    return [pixel[0], pixel[1], pixel[2]]
  }

  this.singleStep = function () {
    this.stepCount += 1

    this.updateStep(
      this.grid[this.currentGrid],
      this.grid[this.currentGrid === 0 ? 1 : 0],
      this.updateRule)
    this.currentGrid = this.currentGrid === 0 ? 1 : 0
  }

  this.animateFunction = function () {
    if (this.autoStep) {
      this.singleStep()
    }
    this.render(0, this.grid[this.currentGrid])
  }

  this.startAnimation = function (time) {
    this.stepCount = 0
    this.randomGrid(this.grid[this.currentGrid])
    if (this.updateEvent === null) {
      this.updateEvent = setInterval(() => this.animateFunction(), time || 10)
    }
  }

  this.render = function () {
    const grid = this.grid[this.currentGrid]

    this.ctx.strokeStyle = 'grey'

    const canvasWidth = this.ctx.canvas.clientWidth;
    const canvasHeight = this.ctx.canvas.clientHeight;
    const gridWidth = grid[0].length
    const gridHeight = grid.length
    const pix = this.imgdata.data

    const tw = canvasWidth * 4
    for (let row = 0; row < gridHeight; row += 1) {
      for (let y = 0; y < this.cellSize; y++) {
        let pos = (tw * this.cellSize * row) + (tw * y)
        for (let col = 0; col < gridWidth; col += 1) {
          const pixel = (this.colorRangeLow == null) ? this.getColor(grid[row][col])
            : this.getColorRange(grid[row][col])
          for (let x = 0; x < this.cellSize; x++) {
            pix[pos] = pixel[0]
            pix[pos + 1] = pixel[1]
            pix[pos + 2] = pixel[2]
            pix[pos + 3] = 255
            pos += 4
          }
        }
      }
    }

    this.ctx.putImageData(this.imgdata, 0, 0)
  }



  this.mouseUp = function (event) {
    console.log(`${currentRule} - ${RULES[currentRule]}`)
    window.ml.init({rule: RULES[currentRule], canvas: canvas, cellSize: zoom, controls:controls})
    currentRule++
    if(currentRule>=RULES.length) {
      currentRule = 0
    }
  }

  this.initEvents = function() {
    this.ctx.canvas.addEventListener('click', (e) => this.mouseUp(e))
  }
  this.init = function (params) {
    this.rows = 0
    this.cols = 0
    this.gridMode = 0

    if (params.canvas == null) {
      this.rows = params.rows || 100
      this.cols = params.cols || 100
      this.autoStep = false
      this.controlsOn = false
    } else {
      this.ctx = params.canvas.getContext('2d')
      this.cellSize = params.cellSize || 5
      this.rows = this.ctx.canvas.height / this.cellSize
      this.cols = this.ctx.canvas.width / this.cellSize
      this.autoStep = true
      this.controlsOn = params.controls === true
      this.imgdata = this.ctx.getImageData(0, 0, this.ctx.canvas.width, this.ctx.canvas.height)
    }

    this.grid = []
    this.grid[0] = MergeLifeRender.zeros([this.rows, this.cols, 3])
    this.grid[1] = MergeLifeRender.zeros([this.rows, this.cols, 3])
    this.mergeGrid = MergeLifeRender.zeros([this.rows, this.cols, 1])
    this.currentGrid = 0
    this.updateRule = null
    this.updateEvent = null
    this.stepCount = 0

    this.randomGrid(this.grid[0])

    const result = this.parseUpdateRule(params.rule)
    this.updateRule = result
  }

  this.postRenderFunction = null
  this.colorRangeLow = null
  this.colorRangeHigh = null
  this.mouseInside = false
}

MergeLifeRender.prototype.KEY_COLOR = [
  [0, 0, 0], // Black 0
  [255, 0, 0], // Red 1
  [0, 255, 0], // Green 2
  [255, 255, 0], // Yellow 3
  [0, 0, 255], // Blue 4
  [255, 0, 255], // Purple 5
  [0, 255, 255], // Cyan 6
  [255, 255, 255] // White 7
]

MergeLifeRender.zeros = function (dimensions) {
  const array = []

  for (let i = 0; i < dimensions[0]; ++i) {
    array.push(dimensions.length === 1 ? 0 : MergeLifeRender.zeros(dimensions.slice(1)))
  }
  return array
}


const canvas = document.getElementById("myCanvas")

  const ctx = canvas.getContext("2d")
  ctx.canvas.width  = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  const RULE = '6da1-0852-5e0f-2Ad9-c902-f8a0-78fd-4473'
  const zoom = 3
  const controls = false

  if (!window.ml) {
    window.ml = new MergeLifeRender()
    window.ml.init({rule: RULE, canvas: canvas, cellSize: zoom, controls:controls})
    window.ml.initEvents()
    window.ml.startAnimation()
  } else {
    window.ml.init({rule: RULE, canvas: canvas, cellSize: zoom, controls:controls})
  }

RULES = [
  'e542-5f79-9341-f31e-6c6b-7f08-8773-7068',
'a07f-c000-0000-0000-0000-0000-ff80-807f',
'6eb6-ba3d-70b4-ac6f-baae-2604-8529-8998',
'ea44-55df-9025-bead-5f6e-45ca-6168-275a',
'7b58-f7b4-c5b4-fd87-22fa-eb10-6de8-107c',
'6eb6-ba3d-70b4-ac6f-baae-2604-8529-8998',
'1c48-9004-8831-41be-2804-8f50-9901-db18',
'df1d-bba1-8e06-aa66-48ff-7414-6a2f-6237',
'6769-5dd6-7d03-564e-a5ec-cae2-54c4-810c',
'cb97-6a74-88c0-28aa-1b6a-834b-4fe8-60ac',
'6007-7d42-05e5-1b9b-2899-e043-1cd4-2f7b',
'dfda-67af-bc97-7ef6-be98-42d9-9147-97d3',
'f81b-38d1-7f60-62ad-850b-2085-ddff-8154',
'548c-aac9-97d2-b8dd-1425-88c1-599d-78e2',
'8501-677e-655f-236e-53ba-d52d-8cf1-1e46',
'5688-0f6c-6619-8605-d7e4-4074-de2e-96c8',
'c168-7b61-b5cc-4e64-8f7a-df90-5362-8750',
'5eb3-2d3b-df40-ee83-e472-60c3-3342-48be',
'5a3d-45de-96fd-de64-ecf9-77c1-8461-9c8c',
'2085-c66a-84d8-fbE8-b3c0-70e4-0e2e-799c',
'5a55-983c-daad-60f5-2969-3077-90e7-9188',
'6da1-0852-5e0f-2Ad9-c902-f8a0-78fd-4473',
'a45d-d552-3331-a34f-890a-bb71-64e2-c4f0',
'd106-f969-cda8-ceb6-9964-977c-cc43-62b1'
]

currentRule = 0
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console