Last active
June 1, 2016 21:15
-
-
Save agnaite/8f99ec4bb0d8a1434a1d6b826c96cf89 to your computer and use it in GitHub Desktop.
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
class TowersOfHanoi | |
attr_reader :towers | |
def initialize | |
@towers = [[4, 3, 2, 1], [], []] | |
end | |
def play | |
from = "" | |
while !win? | |
puts "Select tower to move disc from [1 - 4]: " | |
from = gets.chomp.to_i | |
if !valid?(from) | |
puts "Move invalid. Please select again." | |
play | |
end | |
puts "Select tower to move disc to [1 - 4]: " | |
to = gets.chomp.to_i | |
if !valid?(from, to) | |
puts "Move invalid. Please select again." | |
play | |
else | |
make_move(from, to) | |
end | |
end | |
end | |
def make_move(from, to) | |
@towers[to - 1] << @towers[from - 1].pop | |
p @towers | |
end | |
def win? | |
if @towers[0].empty? | |
if towers[1].empty? || towers[2].empty? | |
puts "YOU WON!" | |
return true | |
end | |
end | |
return false | |
end | |
def valid?(from, to = nil) | |
if to == nil | |
@towers[from - 1].length > 0 | |
else | |
return false if from == to | |
@towers[to - 1].empty? || @towers[from - 1].last < @towers[to - 1].last | |
end | |
end | |
end | |
new_game = TowersOfHanoi.new | |
new_game.play |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment