Created
June 18, 2015 19:40
-
-
Save eddroid/6c8307288fe1ccefc356 to your computer and use it in GitHub Desktop.
C6: Batman REPL Game
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
# display a line on the screen | |
# | |
# refactoring to | |
# - remove some Ruby jargon by defining a | |
# domain-specific-language (DSL) | |
# - remove some repetitive (copy-pasted) code | |
# - have a single place to change the line width | |
def put_a_line | |
puts "*" * 50 | |
end | |
# ask a question, display the valid options | |
# and return the answer | |
# | |
# refactoring a repeated code pattern into a | |
# block "template" | |
def ask_question(question, options) | |
puts question, options | |
# downcase: canonicalize your inputs | |
gets.chomp.downcase | |
end | |
# display a message on the screen | |
# | |
# refactoring to | |
# - implement a REPL game DSL | |
# - do once, apply everywhere | |
# - fix a bug: capitalizing the person name | |
# - refactor an if-statement | |
def say(person, message) | |
puts(person.nil? ? message : "#{person.capitalize}: #{message}") | |
end | |
# display the weapon and the sidekick | |
# | |
# refactoring to implement a game DSL that improves | |
# the readability of the main code below | |
# even if you don't plan to use this method more than | |
# once | |
def display_weapon(weapon, sidekick) | |
case weapon | |
when "batarang" | |
say sidekick, "Awesome! A Batarang! Thanks Batman!" | |
when "flashlight" | |
say sidekick, "Uh... thanks? I'll make sure to keep the light on you." | |
when "fists" | |
say sidekick, "I don't need a weapon! I'll just use my fists like you, Batman!" | |
else | |
say "Don't be selfish. Share your toys with your sidekick." | |
weapon = nil | |
end | |
end | |
##### | |
put_a_line | |
say nil, "After all your hardwork, you've finally become Batman." | |
put_a_line | |
# sanitize/validate your inputs | |
options = ["batgirl", "robin"] | |
begin | |
sidekick = ask_question("Who will be your sidekick?", | |
"BatGirl or Robin") | |
end until options.include? sidekick | |
put_a_line | |
weapon = ask_question("Pick a weapon for your sidekick.", | |
"batarang, flashlight, or fists") | |
display_weapon weapon, sidekick |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment