User:JayCampbell/hexagrid.rb

From Esolang
Jump to navigation Jump to search

Hexagrid

#!/usr/bin/ruby
# Interpreter by Jay Campbell 2008
# for the Hexagrid esoteric programming language

class Hexagrid

    @@grid = [%w{ 0 1 2 3 }, %w{ 4 5 6 7 }, %w{ 8 9 A B }, %w{ C D E F }]

    def initialize
        @stacks = Hash.new
    end

    def parse( string )
        while string =~ /^\s*(\S+)\s*\{([^\}]+)\}\s*;?\s*(.*)/

            output = ''
            stack = @stacks[$1] ||= Hash.new
            data = stack[:data] ||= Array.new
            pointer = stack[:pointer] ||= [0,0]

            $2.split(//).each do |c|
                  if c == '>' then pointer[1] += 1
               elsif c == '<' then pointer[1] -= 1
               elsif c == 'v' then pointer[0] += 1
               elsif c == '^' then pointer[0] -= 1
               elsif c == '!' then pointer = [0,0]; data.clear
               elsif c == '+' then data.unshift  @@grid[pointer[0]][pointer[1]]
               elsif c == 'o' then output << data.join
               end

               # wrap around, not per spec
               # if pointer[0] > 3 then pointer[0] = 0 end
               # if pointer[0] < 0 then pointer[0] = 3 end
               # if pointer[1] > 3 then pointer[1] = 0 end
               # if pointer[1] < 0 then pointer[1] = 3 end

               # verbose/debug
               # p [ c, pointer, data ]
            end
            string = $3
        end
        return output.reverse
    end

    def english( string )
        return parse(string).scan(/.{2}/).collect{ |tuple| tuple.hex.chr }.join
    end
end

hex = Hexagrid.new
while not $stdin.eof?
  puts hex.english(gets)
end

JayCampbell 02:22, 30 November 2008 (UTC)