ruby 中的康威人生游戏

conways game of life in ruby

我正在 ruby 制作康威人生游戏。这是我的 cell_spec.rb 文件。我在第 10 行得到 failure/error 作为:

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

我有另一个文件 cell.rb,其中定义了 class 单元格。如何在此文件中实现自定义谓词数学?

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

这是我的 cell.rb 文件,有单元格 class.. 我想知道死者代码的实现?还活着?方法。请帮帮我

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

这是一种显而易见的方法。 您只需创建一个新的 Cell 实例并存储其状态(如 :dead 或 :alive)。 死的?还活着?方法然后简单地检查状态。

 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