Class: World
- Inherits:
-
Object
- Object
- World
- Defined in:
- lib/world.rb
Overview
class World
Instance Method Summary collapse
-
#clear ⇒ Object
reset the entire world state (all dead).
-
#initialize(width:, height:, init: nil) ⇒ World
constructor
A new instance of World.
-
#iterate ⇒ Object
transition the world from the present state to its next state.
-
#player_score(player) ⇒ Integer
get the current score for a given player.
-
#seed_player(pos:, seed:, char:) ⇒ Object
takes a morphogen seed and puts it (starting at) the given position.
-
#set_player(player: ' ', pos:) ⇒ Object
Set a player at a given position.
-
#state ⇒ WorldState
returns a frozen copy of the world's current state.
Constructor Details
#initialize(width:, height:, init: nil) ⇒ World
Returns a new instance of World
11 12 13 |
# File 'lib/world.rb', line 11 def initialize(width:, height:, init: nil) @state = WorldState.new(width: width, height: height, init: init) end |
Instance Method Details
#clear ⇒ Object
reset the entire world state (all dead)
16 17 18 |
# File 'lib/world.rb', line 16 def clear @state = WorldState.new(width: @state.width, height: @state.height) end |
#iterate ⇒ Object
transition the world from the present state to its next state
57 58 59 60 61 62 63 64 |
# File 'lib/world.rb', line 57 def iterate @state.each_char.each_with_index.each_with_object([]) do |(curr, pos), memo| nxt = @state.next(pos) curr == nxt ? memo : memo << [nxt, pos] end.each do |char, pos| set_player(player: char, pos: pos) end end |
#player_score(player) ⇒ Integer
get the current score for a given player
36 37 38 |
# File 'lib/world.rb', line 36 def player_score(player) @state.count(player) end |
#seed_player(pos:, seed:, char:) ⇒ Object
takes a morphogen seed and puts it (starting at) the given position
44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/world.rb', line 44 def seed_player(pos:, seed:, char:) return unless seed.length == 8 seed.each do |string| return unless string.length == 8 string.each_char do |c| set_player(player: char, pos: pos) if c == 'X' pos += 1 end pos += @state.width - string.length end end |
#set_player(player: ' ', pos:) ⇒ Object
Set a player at a given position
29 30 31 |
# File 'lib/world.rb', line 29 def set_player(player: ' ', pos:) @state[pos] = player end |
#state ⇒ WorldState
returns a frozen copy of the world's current state
22 23 24 |
# File 'lib/world.rb', line 22 def state @state.dup.freeze end |