Connures game of life in ruby

I'm making a conveyor belt game of life in ruby. This is my cell_spec.rb file . I am getting error / error on line 10 like:

expect(GameOfLife::Cell.new_dead_cell).to be_dead 

      

I have another file cell.rb where a class cell is defined. How do I implement a custom mather predicate in this file?

require 'spec_helper'

describe GameOfLife::Cell do 
  def build_neighbours(live_count)
    [GameOfLife::Cell.new_live_cell] * live_count +
       [GameOfLife::Cell.new_dead_cell] * (8 - live_count)
  end
  context "factory" do
    it "can be dead" do
      expect(GameOfLife::Cell.new_dead_cell).to be_dead
    end

    it "can be alive" do
      expect(GameOfLife::Cell.new_live_cell).to be_alive
    end
  end

  context "live cell generation rules" do
    let(:cell) { GameOfLife::Cell.new_live_cell }

    [0, 1].each do |i|
      it "dies when there are #{i} live neighbours" do
        expect(cell.next_generation(build_neighbours(i))).to be_dead
      end
    end

    [2, 3].each do |i|
      it "lives when there are #{i} live neighbours" do
        expect(cell.next_generation(build_neighbours(i))).to be_alive
      end
    end

    (4..8).each do |i|
      it "dead when there are #{i} live neighbours" do
        expect(cell.next_generation(build_neighbours(i))).to be_dead
      end
    end
  end

  context "dead cell generation rules" do
    let(:cell) { GameOfLife::Cell.new_dead_cell }

    (0..2).each do |i|
      it "dies when there are #{i} live neighbours" do
        expect(cell.next_generation(build_neighbours(i))).to be_dead
      end
    end

    [3].each do |i|
      it "lives when there are #{i} live neighbours" do
        expect(cell.next_generation(build_neighbours(i))).to be_alive
      end
    end

    (4..8).each do |i|
      it "dead when there are #{i} live neighbours" do
        expect(cell.next_generation(build_neighbours(i))).to be_dead
      end
    end
  end
end

      

This is my cell.rb file with the cell class. I want to know how to implement dead code? and alive? methods. Plz help me

class GameOfLife::Cell
  ALIVE = "alive"
  DEAD = "dead"

 # lost implementation
  def self.new_dead_cell
     return DEAD
  end

  def self.new_live_cell
    return ALIVE
  end

  def dead?

  end

  def alive?

  end

 end

      

+3


source to share


1 answer


Here's one obvious way to do it. You just create a new Cell instance and save its state (like: dead or: alive). dead? and alive? then just check the status.



 class Cell
  ALIVE = :alive
  DEAD = :dead

  def self.new_dead_cell
     new(DEAD)
  end

  def self.new_live_cell
    new(ALIVE)
  end

  def initialize state
    @state = state
  end
  attr_reader :state

  def dead?
    state == DEAD
  end

  def alive?
    state == ALIVE
  end
end

      

0


source







All Articles