110 lines
2.7 KiB
Ruby
110 lines
2.7 KiB
Ruby
#hangman game
|
|
#01/21/2022
|
|
|
|
def pick_word(a)
|
|
rand_int = rand(0..a.size) #pick a num within the range of the file length
|
|
return a[rand_int].chop! #and format the word
|
|
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 guess
|
|
word.length.times do |i|
|
|
if word[i] == letter #if you find one, replace it with a the letter in the string
|
|
scrambled_word[i] = letter
|
|
end
|
|
end
|
|
end
|
|
return scrambled_word
|
|
end
|
|
|
|
def print_hangman(wrong_guesses)
|
|
man = [" o\n", " \\", "@", "/\n", " /", " \\"] #ascii art of a hangman rope
|
|
puts "_______"
|
|
puts " | "
|
|
wrong_guesses.times do |i|
|
|
print "#{man[i]}"
|
|
end
|
|
end
|
|
|
|
a = Array.new
|
|
dict = File.open('5desk.txt')
|
|
dict.each do |row| #loading the dict file into an array
|
|
a.push(row)
|
|
end
|
|
|
|
word = pick_word(a)
|
|
until word.length.between?(5, 12) #picking a word between 5 and 12 characters long
|
|
word = pick_word(a)
|
|
end
|
|
word.downcase!
|
|
|
|
#initialize some variables
|
|
guess = ""
|
|
guesses = Array.new
|
|
wrong_guesses = 0
|
|
scrambled_word = ""
|
|
scrambled_word << word
|
|
|
|
hidden_letters = generate_hidden_letters(word)
|
|
scrambled_word = scramble_word(word, hidden_letters, scrambled_word)
|
|
|
|
print "\n\nWord is #{word}\n" #cheating XD
|
|
|
|
while true
|
|
|
|
#puts the array as a readable string
|
|
print"\n"
|
|
puts scrambled_word.inspect[1...-1].gsub('"',"").gsub(',','')
|
|
|
|
#check game end conditions
|
|
if hidden_letters.size == 0
|
|
puts "YOU WIN"
|
|
exit
|
|
end
|
|
|
|
if wrong_guesses > 5
|
|
puts "YOU HANG"
|
|
exit
|
|
end
|
|
|
|
print "Guess a letter: " #get player input
|
|
guess = gets.chop
|
|
|
|
unless guesses.include?(guess) #keep track of previous guesses
|
|
guesses.push(guess)
|
|
end
|
|
|
|
#if guess is wrong, add another piece to the hangman
|
|
unless word.include?(guess)
|
|
wrong_guesses = wrong_guesses + 1
|
|
end
|
|
|
|
print "\n\nGuesses: #{guesses.inspect[1...-1].gsub('"',"").gsub(',','')}\n"
|
|
scrambled_word = unscramble_word(word, guesses, scrambled_word)
|
|
print_hangman(wrong_guesses) #^add correct letters to the board
|
|
hidden_letters.delete(guess) #and remove guessed letters from the hidden_letters array
|
|
|
|
end
|
|
|