Skip to content

Instantly share code, notes, and snippets.

@kingcons
Created April 20, 2016 00:17
Show Gist options
  • Save kingcons/695edbe924e9967e833b9b83a55a68f5 to your computer and use it in GitHub Desktop.
Save kingcons/695edbe924e9967e833b9b83a55a68f5 to your computer and use it in GitHub Desktop.
## Hangman
## Data
# * answer
# * guesses
# * maximum number of wrong guesses
# * word_list / dictionary
WORD_LIST = [
"buffalo", "laptop", "programming", "gambino",
"cookies", "damn", "bourbon", "sandwiches",
"internet", "puppies", "ruby", "trumpet",
"onomatopoeia", "disestablishmentarianism"
]
## Actions
# * greeting
# * select a random word
# * until the game ends
# * show the player the game
# * prompt for a guess
# * lose a turn if they guess wrong
# * tell the player what happened
def greeting
puts "Welcome to Hangman!"
puts "I'm too lazy to explain the rules. Just guess some letters."
end
def win?(answer, guesses)
# winner = true
# answer.chars.each do |letter|
# winner = false unless guesses.include?(letter)
# end
# winner
answer.chars.all? do |letter|
guesses.include?(letter)
end
end
def lose?(turns_left)
turns_left.zero? ## turns_left == 0
end
def game_over?(answer, guesses, turns_left)
### all the letters in the answer have been guessed
### player runs out of turns
win?(answer, guesses) || lose?(turns_left)
end
def show_game(word, turns, guesses)
puts "The word is: #{"-" * word.length}"
puts "You have #{turns} turns left."
puts "You have already guessed: #{guesses.join(", ")}."
end
def take_turn
puts "Please guess a letter: "
gets.chomp
end
def hangman
answer = WORD_LIST.sample
turns_left = 7
guesses = []
greeting
until game_over?(answer, guesses, turns_left)
show_game(answer, turns_left, guesses)
guess = take_turn
guesses << guess # guesses.push(guess)
turns_left -= 1 unless answer.include?(guess)
end
postmortem(answer, guesses)
end
def postmortem(answer, guesses)
if win?(answer, guesses)
puts "Great job!"
else
puts "Better luck next time. The word was: #{answer}"
end
end
hangman
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment