我正在用 Ruby 实现生命游戏,这是我目前所拥有的:
class Cell
attr_accessor :world, :x, :y
def initialize(world=World.new, x=0, y=0)
@world = world
@world.cells << self
@x = x
@y = y
end
def neighbours
@neighbours = []
world.cells.each do |cell|
# Detects neighbour to the north
if self.x == cell.x && self.y == cell.y - 1
@neighbours << cell
end
# Detects neighbour to the north-east
if self.x == cell.x - 1 && self.y == cell.y - 1
@neighbours << cell
end
# Detects neighbour to the east
if self.x == cell.x - 1 && self.y == cell.y
@neighbours << cell
end
# Detects neighbour to the south-east
if self.x == cell.x - 1 && self.y == cell.y + 1
@neighbours << cell
end
# Detects neighbour to the south
if self.x == cell.x && self.y == cell.y + 1
@neighbours << cell
end
# Detects neighbour to the south-west
if self.x == cell.x + 1 && self.y == cell.y + 1
@neighbours << cell
end
# Detects neighbour to the west
if self.x == cell.x + 1 && self.y == cell.y
@neighbours << cell
end
# Detects neighbour to the north-west
if self.x == cell.x + 1 && self.y == cell.y - 1
@neighbours << cell
end
end
@neighbours
end
def alive?
self.world.cells.include?(self)
end
def dead?
!self.world.cells.include?(self)
end
def die!
self.world.cells.delete(self)
end
def revive!
self.world.cells << self
end
end
class World
attr_accessor :cells
def initialize
@cells = []
end
def tick!
self.cells.each do |cell|
# Rule 1
if cell.neighbours.count < 2
cell.die!
end
end
end
end
我在 Rails 中编码已经有一段时间了,但我对如何做以下事情感到困惑:
- 验证并确保在 World 的一个字段上只能存在一个 Cell 对象?
- 如何将东西保存到数据库(例如 postgresql)?在这种情况下我是否必须这样做,或者我可以保留它并在内存中运行它吗?
- 如何使我的生命游戏的图形输出看起来像这样?
我感到困惑的原因是因为 Rails 开箱即用,现在我只需要了解 Ruby 是如何做到这一点的帮助。
编辑:
我已经用验证方法更新了 Cell 类,但我只能在初始化对象后运行它。有没有办法在初始化时运行它?这是代码:
5 def initialize(world=World.new, x=0, y=0) | 53 neighbour_cell = Cell.new(subject.world, -1, 0)
6 @world = world | 54 subject.neighbours.count.should == 1
7 @world.cells << self # if self.valid? < this after if doesn't work | 55 end
8 @x = x | 56
9 @y = y | 57 it 'Detects cell to the north-west' do
10 end | 58 neighbour_cell = Cell.new(subject.world, -1, 1)
11 | 59 subject.neighbours.count.should == 1
12 def valid? | 60 end
13 @valid = true | 61
14 self.world.cells.each do |cell| | 62 it 'Creates a live cell' do
15 if self.x == cell.x && self.y == cell.y | 63 cell.should be_alive
16 @valid = false | 64 end
17 self.world.cells.delete(self) | 65
18 end | 66 it 'Kills a cell' do
19 end | 67 cell.die!
20 @valid | 68 cell.should be_dead
21 end