Last active
September 13, 2018 03:57
-
-
Save phluid61/d36234feb023952bfccb103769fda63f to your computer and use it in GitHub Desktop.
Redwine's assignment, done in Ruby
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
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]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.cs.wcupa.edu/rburns/Game/assignments/hw1/