Skip to content

Instantly share code, notes, and snippets.

@jingxia1219
Last active June 18, 2018 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingxia1219/d83b6c7d5b3687f91d4d0e944ef713ad to your computer and use it in GitHub Desktop.
Save jingxia1219/d83b6c7d5b3687f91d4d0e944ef713ad to your computer and use it in GitHub Desktop.
class Hanoi
def initialize
@disc = Array.new(3) {Array.new(1)}
@disc[0] = (1..3).to_a.reverse
choose_mode
play
end
def choose_mode
puts "Welcome to Hanoi! It starts with 3 discs, would you like to play more?\ny/n?"
answer = gets.chomp.downcase
case answer
when "y"
puts "How many discs would you like to to play with? Enter a number > 3"
number = gets.chomp.to_i
@disc = Array.new(3) {Array.new(1)}
@disc[0] = (1..number).to_a.reverse
when "n" then @disc
end
display_game
end
def display_game
p @disc
end
def ask_for_moves
puts "Which pile do you want to move from? (Enter number between 1 ~ 3) "
@start_pile = gets.chomp.to_i - 1
puts "And which pile you like to move it to? (Enter number between 1 ~ 3)"
@end_pile = gets.chomp.to_i - 1
end
def move_disc
disc_to_move = @disc[@start_pile].pop
if @disc[@end_pile].last == nil || @disc[@end_pile].empty?
@disc[@end_pile][0] = disc_to_move
elsif disc_to_move < @disc[@end_pile].last
@disc[@end_pile].push(disc_to_move)
else
@disc[@start_pile].push(disc_to_move)
puts "You can't place a bigger disc on top of a smaller one \nTry again!"
puts "\n"
display_game
ask_for_moves
end
display_game
end
def play
until win?
ask_for_moves
move_disc
end
puts "You Won! Play again?\ny/n?"
play_again = gets.chomp.downcase
case play_again
when "y" then Hanoi.new
when "n" then exit
end
end
def win?
@disc.first.empty? && @disc[1..2].any?(&:empty?)
end
end
game = Hanoi.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment