Skip to content

Instantly share code, notes, and snippets.

@mike1011
Last active June 7, 2017 15:57
Show Gist options
  • Save mike1011/7dba109a9e18cca69ae0cb77c83a0cdd to your computer and use it in GitHub Desktop.
Save mike1011/7dba109a9e18cca69ae0cb77c83a0cdd to your computer and use it in GitHub Desktop.
toy robot on a table created by mike1011 - https://repl.it/Iafm/11
##DIRECTION
class A
def initialize(sym, dx, dy, left, right)
@name, @dx, @dy, @left, @right = sym.to_s, dx, dy, left, right
end
def to_s
@name
end
def left
A.const_get(@left)
end
def right
A.const_get(@right)
end
def advance(x, y)
[x + @dx, y + @dy]
end
@all = [
[:EAST, +1, 0],
[:NORTH, 0, +1],
[:WEST, -1, 0],
[:SOUTH, 0, -1],
]
@all.each_with_index do |(sym, dx, dy), i|
self.const_set(sym,
A.new(sym, dx, dy, @all[(i + 1) % @all.size].first,
@all[(i - 1) % @all.size].first))
end
class << self
def [](name)
A.const_get(name) if A.const_defined?(name)
end
end
end
class Invalid < Exception ; end
# Mixin for toy
##COMMANDS
module B
def place(x, y, face)
validate(x = (x.to_i if /\A\d+\Z/.match(x)),
y = (y.to_i if /\A\d+\Z/.match(y)),
face = A[face.upcase])
@x, @y, @face = x, y, face
end
def move
raise Invalid.new unless @face
new_x, new_y = @face.advance(@x, @y)
validate(new_x, new_y, @face)
@x, @y = new_x, new_y
end
def left
raise Invalid.new unless @face
@face = @face.left
end
def right
raise Invalid.new unless @face
@face = @face.right
end
def report
raise Invalid.new unless @face
puts "Current position===> POSITION X:#{@x}, POSITION Y:#{@y}, FACING:#{@face} ======"
end
end
##FOR TOY ROBOT
class C
include B
def initialize(board_size=5, output=STDOUT)
@board_size = board_size
@output = output
end
def execute(cmd)
cmd = cmd.strip.downcase
op, args = cmd.split(/\s+/, 2)
args = args.split(/\s*,\s*/) if args
raise Invalid.new unless B.public_method_defined?(op)
begin
send(op, *args)
rescue ArgumentError
raise Invalid.new
end
end
def execute_script(io)
io.each_line do |line|
begin
execute(line)
rescue Invalid
#puts "(Ignored invalid)"
end
end
end
private
def validate(x, y, f)
raise Invalid.new unless x && y && f
raise Invalid.new unless (0..@board_size) === x
raise Invalid.new unless (0..@board_size) === y
end
end
C.new.execute_script(ARGF)
@mike1011
Copy link
Author

mike1011 commented Jun 7, 2017

TRY THE ABOVE CODE HERE - https://repl.it/Iafm/16

EXAMPLE -

REPORT
Current position===> POSITION X:0, POSITION Y:0, FACING:NORTH ======
PLACE 0,4,EAST
MOVE
LEFT
MOVE
REPORT
Current position===> POSITION X:1, POSITION Y:5, FACING:NORTH ======

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment