Class: BFunj

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

Constant Summary collapse

COMMAND_MAP =
{ '>'  => :go_left,
'<'  => :go_right,
'^'  => :go_up,
'v'  => :go_down,
'?'  => :go_random,
'_'  => :horizontal_if,
'|'  => :vertical_if,
'+'  => :add,
'-'  => :subtract,
'*'  => :multiply,
'/'  => :divide,
'%'  => :modulo,
'!'  => :negate,
'`'  => :test_greater_than,
':'  => :duplicate,
'\\' => :swap,
'$'  => :discard,
'#'  => :skip,
'&'  => :input,
'.'  => :output,
'@'  => :stop }.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ BFunj

Returns a new instance of BFunj.



35
36
37
38
39
40
41
42
43
44
# File 'lib/bfunj.rb', line 35

def initialize options = {}
  @pc = { :row => 0, :col => 0 }
  @direction = :left
  @distance = 1
  @stack = Stack.new
  @max_steps = options[:max_steps] || 0
  @input_stream = options[:input_stream] || $stdin
  @output_stream = options[:output_stream] || $stdout
  load_file(options[:filename]) if options[:filename]
end

Instance Attribute Details

#programObject (readonly)

Returns the value of attribute program.



33
34
35
# File 'lib/bfunj.rb', line 33

def program
  @program
end

#stackObject (readonly)

Returns the value of attribute stack.



33
34
35
# File 'lib/bfunj.rb', line 33

def stack
  @stack
end

Instance Method Details

#load_file(filename) ⇒ Object



46
47
48
49
50
# File 'lib/bfunj.rb', line 46

def load_file filename
  @program = File.open(filename).readlines.map { |l| l.chomp }
  @height = @program.size
  @width = @program[0].size
end

#runObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/bfunj.rb', line 52

def run
  steps = 0
  @done = false
  loop do
    @distance = 1
    command = @program[@pc[:row]][@pc[:col]]
    process_command command
    advance_pc
    if @max_steps != 0
      steps += 1
      break if steps > @max_steps || @done
    end
  end
end