Skip to content

Instantly share code, notes, and snippets.

@phluid61
Last active September 13, 2018 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phluid61/d36234feb023952bfccb103769fda63f to your computer and use it in GitHub Desktop.
Save phluid61/d36234feb023952bfccb103769fda63f to your computer and use it in GitHub Desktop.
Redwine's assignment, done in Ruby
all_words = File.open('dictionary.txt', 'r') {|f| f.each_line.map{|l|l.strip}.to_a }
all_words.reject! {|w| w.nil? || w == '' }
# --- prompt and initialise
candidates = []
while candidates.empty?
print "Word length: "
length = STDIN.gets.to_i
if length <= 0 || (candidates = all_words.select {|w| w.length == length}).empty?
puts "That's silly."
end
end
correct = [nil] * length
used = {}
lives = 0
while lives <= 0
print "Incorrect guesses: "
lives = STDIN.gets.to_i
if lives <= 0
puts "That's silly."
end
end
show_num = nil
while show_num.nil?
print "Show number of possible words? [Y/N] "
ans = STDIN.gets[0].downcase
if ans == 'y'
show_num = true
elsif ans == 'n'
show_num = false
end
end
# --- game loop
while lives > 0
puts ""
puts "You have #{lives} incorrect guess#{lives == 1 ? '' : 'es'} left."
puts "[\# word possible: #{candidates.length}]" if show_num
puts "Word: #{correct.map{|c| c.nil? ? '_' : c}.join(' ')}"
puts "Used letters: #{used.keys.sort.join(' ')}"
print "Enter guess: "
char = STDIN.gets[0].downcase
if char !~ /[a-z]/
puts "That's not a letter."
elsif used[char]
puts "You've already tried #{char}."
else
used[char] = 1
# Categories candidate words into families
families = {}
candidates.each do |word|
template = word.tr "^#{char}", '-'
families[template] ||= []
families[template] << word
end
# Select a family (in this case, largest)
family = families.max_by{|template, list| list.length }
candidates = family[1]
# Reward or Punishment
if family[0].gsub('-', '') == ''
puts "Sorry, there are zero."
lives -= 1
else
puts "You guessed a letter correctly!"
family[0].each_char.with_index do |char, idx|
correct[idx] = char if char != '-'
end
# Maybe game over (in a good way?)
break unless correct.find_index(nil)
end
end
end
puts "Game over"
puts "The word is #{candidates[rand candidates.length]}"
@phluid61
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment