ruby 康威的生命游戏 - 版本1

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 康威的生命游戏 - 版本1相关的知识,希望对你有一定的参考价值。

# pnm library converts array to image in ruby
require "pnm"

class Universe
   def initialize(row, column, percentFill)
      @init_row = row
      @init_column = column 
      @image = Array.new(row) { Array.new(column,0) }
      @initialSeed = (percentFill*@init_row*@init_column/100).to_i
      @initialSeed.times do |i|
         rand_row = rand(0..@init_row-1)
         rand_column = rand(0..@init_column-1)
         @image[rand_row][rand_column]=1     
      end
      @options = {:type => "pbm"}
   end

   def printme(input)
    image2 = PNM.create(@image)
    str = input.to_s.rjust(4, "0")
    image2.write_with_extension(str)
   end

  def generate_next_frame
    newframe = Marshal.load(Marshal.dump(@image))
    @image.each_with_index do |x, xi|
      x.each_with_index do |y, yi|
          neighbors = check_live_neighbors(xi,yi)
        if @image[xi][yi] == 1
          if  neighbors < 2 || neighbors > 3
            newframe[xi][yi] = 0
          end
        else
          if neighbors == 3
            newframe[xi][yi] = 1
          end
        end
      end
    end
    @image = Marshal.load(Marshal.dump(newframe))
  end

  def check_live_neighbors(row,column)
    neighbors = {:n => 0, :e=>0,:w=>0, :s=>0, :ne=>0, :nw=>0, :se=>0, :sw=>0}
    if row>0 
     neighbors[:n] = @image[row-1][column]
    end
    if row<@init_row-1
     neighbors[:s] = @image[row+1][column]
    end
    if column<@init_column-1
     neighbors[:e] = @image[row][column+1]
   end
    if column>0
     neighbors[:w] = @image[row][column-1]
   end
   if row>0 && column<@init_column-1
     neighbors[:ne]= @image[row-1][column+1]
   end
   if row>0 && column>0
     neighbors[:nw]= @image[row-1][column-1]
   end
   if row<@init_row-1 && column<@init_column-1
     neighbors[:se]= @image[row+1][column+1]
   end
   if row<@init_row-1 && column>0
     neighbors[:sw]= @image[row+1][column-1]
   end
    neighbors.values.inject(:+)
  end
end

# execution

u = Universe.new(200,200,20)
i = 0

while (i <200) do
u.generate_next_frame
u.printme(i)
i +=1
end

以上是关于ruby 康威的生命游戏 - 版本1的主要内容,如果未能解决你的问题,请参考以下文章

康威的生命游戏:为啥模式行为不正确?

康威生命游戏_学习记录

优化康威的“生命游戏”

为啥康威的生命游戏可以归类为万能机?

康威生命游戏的简单动画与 FuncAnimation

Python案例:协程实现康威生命游戏,元胞自动机