Skip to content

Instantly share code, notes, and snippets.

@kvirani
Last active April 8, 2018 02:21
Show Gist options
  • Save kvirani/5715487 to your computer and use it in GitHub Desktop.
Save kvirani/5715487 to your computer and use it in GitHub Desktop.
class Hangman
LIST = ["canada", "england", "australia", "japan"]
attr_accessor :word, :chances, :board, :list, :guesses, :answer
class InvalidGuessException < Exception
end
def initialize()
@chances = 8
@guesses = []
@word = LIST.sample
#puts "WORD: ", @word
@board = setup_board(@word)
end
# return @guesses as a string
def guesses
@guesses.join(' ')
end
# if the word has the given letter, put it on the board, otherwise, it's a wrong guess
def guess(letter)
raise InvalidGuessException.new("Invalid Guess!") unless valid_guess?(letter)
if word_has?(letter)
put_letter_on_board(letter)
else
wrong_letter(letter) if !@guesses.include? letter
end
end
# return true if @board doesn't have a '_', otherwise return false
def win?
!@board.include? '_'
end
# return true if @chances is 0, otherwise return false
def lost?
@chances == 0
end
private
def valid_guess?(letter)
letter.length == 1
end
# replace indexes of @board with letter where the same indexes of @word are letter
# in other words, if @board is _ _ _ _ _ _ and @word is canada
# and the letter guessed is a
# then @board should become _ a _ a _ a
def put_letter_on_board(letter) # -> a
for i in (0..@word.length)
@board[i] = letter if @word[i] == letter
end
end
# return true if word has letter
def word_has?(letter)
@word.include? letter
end
# return a string of underscores equal to length of the given word
def setup_board(word)
'_' * @word.length
end
# decrement # of chances and add letter to guesses
def wrong_letter(letter)
@chances -= 1
@guesses << letter
end
end
# require 'pry' <= Uncomment if you want to debug
require_relative "hangman"
#figure out a random word to use for the game
class HangmanRunner
# Starts the hangman game
def self.run
@game = Hangman.new()
while true
puts "\nBoard: #{@game.board}\n\n"
puts "Guessed letters: #{@game.guesses}\n\n"
puts "Chances: #{@game.chances}\n\n"
print "Take your best shot! Enter guess: "
#binding.pry
letter = gets.chomp
# Hangman#guess may throw an exception when it's an invalid guess.
begin
@game.guess(letter)
rescue Hangman::InvalidGuessException => e
puts e.message
end
if @game.win?
puts "\n\nCongratulations! You won!\n"
break
elsif @game.lost?
puts "\n\nYou lost. The word was #{@game.word}\n"
break
end
puts "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"
end
end
end
HangmanRunner.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment