Class: GameOfGithubLife::Game

Inherits:
Object
  • Object
show all
Defined in:
lib/game_of_github_life/game.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(field) ⇒ Game

Returns a new instance of Game.



11
12
13
14
15
16
17
18
19
# File 'lib/game_of_github_life/game.rb', line 11

def initialize(field)
  @field = field
  @x_size = 0..field.length - 1
  @y_size = 0..field.first.length - 1
  @prev_prev_footprint = 0
  @previous_footprint = 0
  @step = 0
  check_end
end

Instance Attribute Details

#stepObject

Returns the value of attribute step.



9
10
11
# File 'lib/game_of_github_life/game.rb', line 9

def step
  @step
end

#x_sizeObject (readonly)

Returns the value of attribute x_size.



7
8
9
# File 'lib/game_of_github_life/game.rb', line 7

def x_size
  @x_size
end

#y_sizeObject (readonly)

Returns the value of attribute y_size.



8
9
10
# File 'lib/game_of_github_life/game.rb', line 8

def y_size
  @y_size
end

Class Method Details

.field_footprint(field) ⇒ Object



3
4
5
# File 'lib/game_of_github_life/game.rb', line 3

def self.field_footprint(field)
  field.map(&:join).join.to_i(2)
end

Instance Method Details

#ended?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/game_of_github_life/game.rb', line 38

def ended?
  ended
end

#neighbors(x, y) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/game_of_github_life/game.rb', line 42

def neighbors(x, y)
  [
      [x - 1, y - 1],
      [x - 1, y],
      [x - 1, y + 1],
      [x, y - 1],
      [x, y + 1],
      [x + 1, y - 1],
      [x + 1, y],
      [x + 1, y + 1],
  ].select { |(a, b)| x_size.cover?(a) && y_size.cover?(b) }
      .map { |(a, b)| field[a][b] }
end

#nextObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/game_of_github_life/game.rb', line 21

def next
  return field if ended?

  self.step += 1

  self.field = field.each_with_index.map do |row, x|
    row.each_with_index.map do |prev, y|
      sum = neighbors(x, y).sum
      ((3 - prev)..3).cover?(sum) ? 1 : 0
    end
  end

  check_end

  field
end