Skip to content

Instantly share code, notes, and snippets.

@hyrious
Last active July 23, 2017 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyrious/d432db8562965b746976380a5ee1604a to your computer and use it in GitHub Desktop.
Save hyrious/d432db8562965b746976380a5ee1604a to your computer and use it in GitHub Desktop.
class Befunge
attr_accessor :x, :y, :stack, :d, :ans, :code
def initialize code
@x, @y, @stack, @d, @ans, @code = 0, 0, [], '>', '', code.lines.map(&:chomp)
end
def c
@code[y][x]
end
def m
case d
when '>' then @x = (x + 1) % @code[y].length
when '<' then @x = (x - 1) % @code[y].length
when '^' then @y = (y - 1) % @code.size
when 'v' then @y = (y + 1) % @code.size
end
end
def interpret!
while c != '@'
# puts "#{ans} | #{c} | #{stack.join(' ')}"
case c
when '0'..'9' then @stack.push c.to_i
when '+', '-', '*', '/', '%' then @stack.push _ = @stack.pop(2).inject(c) rescue 0
when '!' then @stack.push @stack.pop.zero? ? 1 : 0
when '`' then @stack.push @stack.pop(2).inject(:>) ? 1 : 0
when '^', 'v', '<', '>' then @d = c
when '?' then @d = ['^', 'v', '<', '>'].sample
when '_' then @d = @stack.pop.zero? ? '>' : '<'
when '|' then @d = @stack.pop.zero? ? 'v' : '^'
when '"' then m; (@stack.push c.ord; m) while c != '"'
when ':' then @stack.push @stack.last || 0
when '\\' then @stack.size == 1 ? @stack.push(0) : @stack.concat(@stack.pop(2).reverse)
when '$' then @stack.pop
when '.' then @ans.concat @stack.pop.to_s
when ',' then @ans.concat @stack.pop.chr
when '#' then m
when '&' then @stack.push gets.to_i
when 'p' then @stack.pop(3).tap { |v, x, y| @code[y][x] = v.chr }
when 'g' then @stack.pop(2).tap { |x, y| @stack.push @code[y][x].ord }
end
m
end
self
end
def self.interpret code
new(code).interpret!.ans
end
end
def interpret(code)
Befunge.interpret(code)
end
puts interpret <<-EOF
2>:3g" "-!v\\ g30 <
|!`"O":+1_:.:03p>03g+:"O"`|
@ ^ p3\\" ":<
2 234567890123456789012345678901234567890123456789012345678901234567890123456789
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment