diff --git a/Nicks-Game/controller.rb b/Nicks-Game/controller.rb new file mode 100644 index 0000000..2295118 --- /dev/null +++ b/Nicks-Game/controller.rb @@ -0,0 +1,38 @@ +require_relative 'view' +require_relative 'model' + +class GameController + include GameView + + def run! + hangman = Hangman.new + + Print::run_spinner + Print::title_screen + + loop do + Print::menu + case Print::fetch_user_input + when "P" + hangman.reset + Print::play(hangman.play) + loop do + hangman.guess(Print::fetch_user_input) + if hangman.done + Print::finish(hangman.word) + break + else + Print::play(hangman.play) + end + end + when "Q" + puts "We're done" + exit + else + Print::error_message + end + end + end +end + +GameController.new.run! diff --git a/Nicks-Game/model.rb b/Nicks-Game/model.rb new file mode 100644 index 0000000..585af2e --- /dev/null +++ b/Nicks-Game/model.rb @@ -0,0 +1,46 @@ +class Hangman + attr_reader :word, :guessed + MAX_TRIES = 10 + + def initialize + @word = File.readlines('words.txt').sample.strip.upcase + @letters_left = @word.dup + @guessed = [] + @tries = 0 + end + + # apply a user's guessed character + def guess(char) + @guessed.push(char) + @tries += 1 + @letters_left.delete! char + end + + # is the game over? + def done + @tries >= MAX_TRIES || guessmatch + end + + # do the user's combined guesses reveal the secret word? + def guessmatch + @letters_left.empty? + end + + # start a new game + def reset + initialize + end + + # sends hash of gamestate (string, tries) through controller to view + def play + playString = '' + word.chars.each do |letter| + if guessed.include?(letter) + playString += letter + ' ' + else + playString += '_ ' + end + end + { playString: playString, tries: MAX_TRIES - @tries } + end +end diff --git a/Nicks-Game/view.rb b/Nicks-Game/view.rb new file mode 100644 index 0000000..6024ae4 --- /dev/null +++ b/Nicks-Game/view.rb @@ -0,0 +1,57 @@ +module GameView + + module Print + + class << self + def run_spinner + print "Loading (please wait) " + 5.times { print "."; sleep 0.5; } + print "\n" + end + + def error_message + puts "That's not a command key. Try again!" + end + + def title_screen +title = < " + gets.chomp.upcase + end + end + end +end diff --git a/Nicks-Game/words.txt b/Nicks-Game/words.txt new file mode 100644 index 0000000..3a9a451 --- /dev/null +++ b/Nicks-Game/words.txt @@ -0,0 +1,8 @@ +cats +dogs +moose +geese +horses +elephants +tarsiers +armadillos