Skip to content

Instantly share code, notes, and snippets.

@webdevlasse
Last active December 31, 2015 23:09
Show Gist options
  • Save webdevlasse/8058142 to your computer and use it in GitHub Desktop.
Save webdevlasse/8058142 to your computer and use it in GitHub Desktop.
Code quiz for Kabam
#!/usr/bin/env ruby
DIRECTIONS =['N', 'E', 'S', 'W']
class Hero
def initialize(x,y,direction)
@x = x
@y = y
@direction = direction
end
def turn(input)
direction = @new_direction ||= @direction
hash = Hash[DIRECTIONS.map.with_index.to_a]
if input == 'L'
new_direction_key = hash[direction] - 1
else
new_direction_key = hash[direction] + 1
end
if new_direction_key == 4
@new_direction = 'N'
else
@new_direction = DIRECTIONS[new_direction_key]
end
end
def move(input)
if input != "M"
turn(input)
else
move_forward_one
end
end
def move_forward_one
direction = @new_direction ||= @direction
if direction == 'N'
@y = @y + 1
elsif direction == 'S'
@y = @y - 1
elsif direction == 'E'
@x = @x + 1
else direction == 'W'
@x = @x - 1
end
@direction = @new_direction
new_coordinates = @x.to_s+ ' ' + @y.to_s + ' ' + @direction
end
end
h1 = Hero.new 1,2,'N'
h2 = Hero.new 3,3,'E'
h1.move 'L'
h1.move 'M'
h1.move 'L'
h1.move 'M'
h1.move 'L'
h1.move 'M'
h1.move 'L'
h1.move 'M'
puts h1.move 'M'
puts "*****"
h2.move 'M'
h2.move 'M'
h2.move 'R'
h2.move 'M'
h2.move 'M'
h2.move 'R'
h2.move 'M'
h2.move 'R'
h2.move 'R'
puts h2.move 'M'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment