Last active
December 31, 2015 23:09
-
-
Save webdevlasse/8058142 to your computer and use it in GitHub Desktop.
Code quiz for Kabam
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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