Class: RubyFunge::RubyFunge

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

Constant Summary collapse

DIRS =
[:left, :right, :up, :down]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRubyFunge

Returns a new instance of RubyFunge.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rubyfunge/rubyfunge.rb', line 10

def initialize()
  @x, @y    = 0, 0
  @dir      = :right
  @code     = []
  @stack    = []
  @str_mode = false
  @skip     = false

  @synt   = {
              '+'=>:op_add, '-'=>:op_sub, '*'=>:op_mul, '/'=>:op_div, '%'=>:op_mod,
              '!'=>:op_not, '`'=>:op_gt,
              '>'=>:op_right, '<'=>:op_left, '^'=>:op_up, 'v'=>:op_down,
              '?'=>:op_rnd,
              '_'=>:op_lr, '|'=>:op_ud,
              '"'=>:op_str,
              ':'=>:op_dup, '\\'=>:op_swp,
              '$'=>:op_pop, '.'=>:op_outi, ','=>:op_outc,
              '#'=>:op_skp, 'p'=>:op_put, 'g'=>:op_get,
              '&'=>:op_aski, '~'=>:op_askc
            }
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



6
7
8
# File 'lib/rubyfunge/rubyfunge.rb', line 6

def code
  @code
end

#stackObject (readonly)

Returns the value of attribute stack.



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

def stack
  @stack
end

#xObject (readonly)

Returns the value of attribute x.



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

def x
  @x
end

#yObject (readonly)

Returns the value of attribute y.



4
5
6
# File 'lib/rubyfunge/rubyfunge.rb', line 4

def y
  @y
end

Instance Method Details

#run(code) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/rubyfunge/rubyfunge.rb', line 40

def run(code)
  i = 0
  @code = []
  code.each_line {|l|
    @code[i] = l
    i += 1
  }
  @x, @y = 0,0
  while (@code[@y][@x].chr != '@')
    op = @code[@y][@x].chr
    if (@str_mode)
      if (op == '"')
        op_str
      else
        push op[0]
      end
    elsif (op=='#')
      @skip = true
    elsif (op=~/\d/ && !@skip)
      self.send :push, op.to_i
      @skip = false
    else
      self.send @synt[op] if @synt.include?(op) && !@skip
      @skip = false
    end
    case @dir
      when :right
        @x += 1
        @x = 0 if @x > @code[@y].length - 1
      when :left
        @x -= 1
        @x = @code[@y].length - 1 if @x < 0
      when :up
        @y -= 1
        @y = @code.length - 1 if @y < 0
      when :down
        @y += 1
        @y = 0 if @y > @code.length - 1
    end
  end
end

#run_file(filename) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/rubyfunge/rubyfunge.rb', line 32

def run_file(filename)
  if (!File.exist?(filename))
    raise "File does not exist"
  else
    run(File.open(filename).read())
  end
end