Sha256: 49a8893bd325c22cfe9ccac6f741356107d2ed67dcc8cdab5f8009d699ad64da

Contents?: true

Size: 966 Bytes

Versions: 1

Compression:

Stored size: 966 Bytes

Contents

# frozen_string_literal: true

module Conwaymp
  class Cell
    attr_accessor :state, :living_neighbours

    def initialize(state = nil)
      @state = state ||  (0.15 > rand ? :alive : :dead)
      @living_neighbours = 0

      @icons = {
        alive: ' # '.colorize(:green),
        dead: ' . '.colorize(:red)
      }
    end

    def print
      @icons[@state]
    end

    def tick
      die! if underpopulated? || overpopulated?
      rebirth! if repopulate? || survives?
    end

    def underpopulated?
      living_neighbours < 2 && alive?
    end

    def overpopulated?
      living_neighbours > 3 && alive?
    end

    def repopulate?
      living_neighbours == 3 && dead?
    end

    def survives?
      ((2..3).cover? living_neighbours) && alive?
    end

    def alive?
      @state == :alive
    end

    def dead?
      @state == :dead
    end

    def rebirth!
      @state = :alive
    end

    def die!
      @state = :dead
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
conwaymp-0.2.0 lib/conwaymp/cell.rb