私はRuby で Game of Life を実装しています。これまでのところ、次のようなものがあります。
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 でコーディングを行ってきましたが、次のことを行う方法について混乱しています。
- 世界の 1 つのフィールドに 1 つの Cell オブジェクトしか存在できないことを検証して確認しますか?
- 物事をDBに保存する方法(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