Created
June 23, 2014 15:01
-
-
Save jmmastey/a9185fdb46de9c61c9a6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class HackGame | |
attr_reader :options | |
DIFFICULTIES = { | |
very_easy: { word_size: 4, word_count: 5 }, | |
easy: { word_size: 7, word_count: 8 }, | |
medium: { word_size: 10, word_count: 10 }, | |
hard: { word_size: 12, word_count: 13 }, | |
very_hard: { word_size: 15, word_count: 15 }, | |
} | |
DEFAULT_DIFFICULTY = "medium" | |
def initialize(options = {}) | |
@options = { | |
generator: WordListGenerator.new, | |
lives: 4, | |
outputter: STDOUT, | |
inputter: STDIN, | |
}.merge(options) | |
end | |
def play | |
difficulty = get_difficulty | |
words = options[:generator].pick(size: difficulty[:word_size], count: difficulty[:word_count]) | |
play_game(words) | |
end | |
private | |
def get_difficulty | |
difficulties = DIFFICULTIES.keys.map { |key| key.to_s.gsub(/_/, ' ') } | |
out.puts "Valid difficulties are: #{difficulties.join ", " }" | |
out.print "Select a difficulty [#{DEFAULT_DIFFICULTY}]: " | |
difficulty = inn.gets.chomp | |
difficulty = DEFAULT_DIFFICULTY if difficulty.empty? | |
raise unless difficulties.include? difficulty | |
DIFFICULTIES[difficulty.to_sym] | |
end | |
def play_game(words) | |
password = words.sort_by { rand }.first | |
out.puts words.join("\n") | |
lives = options[:lives] | |
lives.downto(1) do |lives| | |
play_round(words, lives, password) | |
end | |
out.puts "BOOM!" | |
end | |
def play_round(words, lives, password) | |
out.print "Guess (#{lives} left)? " | |
guess = inn.gets.chomp | |
if guess == password | |
out.puts "You win!" | |
exit | |
else | |
score = score_hand(password, guess) | |
out.puts "#{score}/#{password.length} correct" | |
end | |
end | |
def score_hand(password, guess) | |
password.chars | |
.zip(guess.chars) | |
.select { |a,b| a == b } | |
.length | |
end | |
def out | |
options[:outputter] | |
end | |
def inn | |
options[:inputter] | |
end | |
end | |
class WordListGenerator | |
def initialize | |
@words = word_list | |
end | |
def pick(options = {}) | |
options = { | |
size: 7, | |
count: 10, | |
}.merge(options) | |
@words.select { |word| word.length == options[:size] } | |
.sort_by { rand } | |
.take options[:count] | |
end | |
def word_list | |
File.read("enable1.txt").lines.map(&:chomp) | |
end | |
end | |
game = HackGame.new | |
game.play |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment