Class: TwentyFortyEight::Dsl

Inherits:
Object
  • Object
show all
Defined in:
lib/TwentyFortyEight/dsl.rb

Overview

Dsl

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(game, settings = {}, &block) ⇒ Dsl

Returns a new instance of Dsl.



7
8
9
10
11
12
# File 'lib/TwentyFortyEight/dsl.rb', line 7

def initialize(game, settings = {}, &block)
  @callable = block
  @sequence = []
  @settings = settings
  @game     = game
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object



59
60
61
62
# File 'lib/TwentyFortyEight/dsl.rb', line 59

def method_missing(sym, *args, &block)
  return info sym     if info? sym
  return sym          if game.dup.action(sym, insert: false).changed?
end

Instance Attribute Details

#gameObject (readonly)

Returns the value of attribute game.



5
6
7
# File 'lib/TwentyFortyEight/dsl.rb', line 5

def game
  @game
end

#settingsObject (readonly)

Returns the value of attribute settings.



5
6
7
# File 'lib/TwentyFortyEight/dsl.rb', line 5

def settings
  @settings
end

Instance Method Details

#apply(game) ⇒ Object



14
15
16
17
# File 'lib/TwentyFortyEight/dsl.rb', line 14

def apply(game)
  @queue = []
  instance_eval(&@callable)
end

#info(sym) ⇒ Object



47
48
49
# File 'lib/TwentyFortyEight/dsl.rb', line 47

def info(sym)
  game.send sym
end

#info?(sym) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/TwentyFortyEight/dsl.rb', line 43

def info?(sym)
  [:won?, :lost?, :changed?, :available, :score, :prev_score].include? sym
end

#quit!Object



51
52
53
# File 'lib/TwentyFortyEight/dsl.rb', line 51

def quit!
  game.quit! && :quit
end

#respond_to_missing?(sym, *args, &block) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/TwentyFortyEight/dsl.rb', line 64

def respond_to_missing?(sym, *args, &block)
  true
end

#run_sequenceObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/TwentyFortyEight/dsl.rb', line 24

def run_sequence
  return @poss.shift if @poss && @poss.any?

  copy   = @sequence.dup
  sample = game.dup
  @poss  = []

  while (next_move = copy.shift)
    unless sample.move(next_move).changed?
      @poss = nil
      break
    end

    @poss << next_move
  end

  @poss && @poss.shift
end

#sequence(*directions) ⇒ Object



19
20
21
22
# File 'lib/TwentyFortyEight/dsl.rb', line 19

def sequence(*directions)
  @sequence = directions.flatten.map(&:to_sym)
  run_sequence
end