hangman/hangman.rb

89 lines
2.0 KiB
Ruby

#hangman game
#01/21/2022
def pick_word(a)
rand_int = rand(0..a.size)
return a[rand_int].chop!
end
def generate_hidden_letters(word)
hidden_letters = Array.new
word.length.times do |i|
if rand(0..1) == 0 #do this 50% of the time
hidden_letters.push(word[i]) #create an array of letters to be hidden
end
end
return hidden_letters
end
def scramble_word(word, hidden_letters, scrambled_word)
hidden_letters.each do |letter| #for each hidden letter
word.length.times do |i|
if word[i] == letter #if you find one, replace it with a "_" in the string
scrambled_word[i] = "_"
end
end
end
return scrambled_word
end
def unscramble_word(word, guesses, scrambled_word)
guesses.each do |letter| #for each hidden letter
word.length.times do |i|
if word[i] == letter #if you find one, replace it with a "_" in the string
scrambled_word[i] = letter
end
end
end
return scrambled_word
end
a = Array.new
dict = File.open('5desk.txt')
dict.each do |row|
a.push(row)
end
#picking a word between 5 and 12 characters long
word = pick_word(a)
until word.length.between?(5, 12)
word = pick_word(a)
end
puts "Your word is #{word}"
#initialize some variables
guess = ""
scrambled_word = ""
scrambled_word << word
guesses = Array.new
hidden_letters = generate_hidden_letters(word)
scrambled_word = scramble_word(word, hidden_letters, scrambled_word)
while true
puts "Word is #{word}"
puts "scrambled is #{scrambled_word}"
#puts the array as a readable string
puts scrambled_word.inspect[1...-1].gsub('"',"").gsub(',','')
print "Guess a letter: "
guess = gets.chop
unless guesses.include?(guess)
guesses.push(guess)
end
p guesses
p hidden_letters
scrambled_word = unscramble_word(word, guesses, scrambled_word)
end
#if input is included in word but not hidden word then
#if word[x] == input then hidden[x] == input
#do this over the array
#if guess == a hidden letter
# fill in that letter
#else
# increase hangman counter