import java.awt._
import java.awt.event.ActionEvent

import javax.swing._

object ElementaryCellularAutomaton extends App {

  SwingUtilities.invokeLater(() =>
    new JFrame("Elementary Cellular Automaton") {

      class ElementaryCellularAutomaton extends JPanel {
        private val dim = new Dimension(900, 450)
        private val cells = Array.ofDim[Byte](dim.height, dim.width)
        private var rule = 0

        private def ruleSet =
          Seq(30, 45, 50, 57, 62, 70, 73, 75, 86, 89, 90, 99, 101, 105, 109, 110, 124, 129, 133, 135, 137, 139, 141, 164, 170, 232)

        override def paintComponent(gg: Graphics): Unit = {
          def drawCa(g: Graphics2D): Unit = {

            def rules(lhs: Int, mid: Int, rhs: Int) = {
              val idx = lhs << 2 | mid << 1 | rhs
              (ruleSet(rule) >> idx & 1).toByte
            }

            g.setColor(Color.black)
            for (r <- 0 until cells.length - 1;
                 c <- 1 until cells(r).length - 1;
                 lhs = cells(r)(c - 1);
                 mid = cells(r)(c);
                 rhs = cells(r)(c + 1)) {
              cells(r + 1)(c) = rules(lhs, mid, rhs)