Last active
June 18, 2018 01:36
-
-
Save jingxia1219/74481ef4308b8d8da02289531b45ad00 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 Hangman | |
def initialize | |
@dictionary = File.open('dictionary.txt').readlines.sample | |
play | |
end | |
def word_length | |
@length = @dictionary.length - 1 | |
@chances = @length + 2 | |
end | |
def board | |
@board = "_ " * @length | |
end | |
def check_guess(letter) | |
arr = [] | |
@dictionary.chars.each_with_index do |el, idx| | |
arr << idx if el == letter | |
end | |
arr.each do |el| | |
@board[el] = letter if el == 0 | |
@board[el*2] = letter | |
end | |
@board | |
end | |
def won? | |
return true unless @board.include?("_") | |
false | |
end | |
def play | |
word_length | |
entries = [] | |
puts "You have #{@chances} chances!" | |
puts board | |
while @chances > 0 | |
puts "Guess a letter:" | |
get_answer = true | |
while get_answer | |
answer = gets.chomp.downcase | |
if entries.include?(answer) | |
puts "You've already used #{answer}, please try a different letter" | |
elsif answer.length != 1 || !("a".."z").include?(answer) | |
puts "Invalid entry, try again:" | |
else | |
get_answer = false | |
end | |
entries << answer | |
end | |
@chances -=1 unless @dictionary.include?(answer) | |
puts check_guess(answer) | |
if won? | |
puts "Bingo! Play again?\n y/n?" | |
play_again = gets.chomp.downcase | |
case play_again | |
when "y" then Hangman.new | |
when "n" then exit | |
end | |
break | |
end | |
if @chances >1 | |
puts "You have #{@chances} chances left" | |
else | |
puts "You have #{@chances} chance left" | |
end | |
end | |
puts "GAME OVER!\nThe secret word was #{@dictionary} Play again?\n y/n?" unless won? | |
play_again = gets.chomp.downcase | |
case play_again | |
when "y" then Hangman.new | |
when "n" then exit | |
end | |
end | |
end | |
new_game = Hangman.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment