Skip to content

Instantly share code, notes, and snippets.

@assadk88
Created July 28, 2019 21:10
Show Gist options
  • Save assadk88/7276bd3c462f3173269247be80acfc48 to your computer and use it in GitHub Desktop.
Save assadk88/7276bd3c462f3173269247be80acfc48 to your computer and use it in GitHub Desktop.
chapter-6--master-quiz-q3
# Write an adventure game that the player plays from the command line
# by typing in the commands `north` and `south`. The game should have
# this behaviour:
# * Two rooms: a passage and a cave.
# * Passage commands
# * `north`: `puts`es `You are in a scary cave.`
# * Cave commands
# * `south`: `puts`es `You are in a scary passage.`
# * `north`: `puts`es 'You walk into sunlight.` and the program
# stops executing.
# * The player starts in the passage.
# * When the player starts the game, the game shouldn't `puts` a room
# description until the player moves between rooms.
# * If the player enters a command that is incorrect for the
# situation, nothing happens and nothing is `puts`ed.
#
# * Note: To stop the program when the user wins, don't use `exit` to
# quit the program because this will break the automated tests. To
# exit a while loop early, use the `break` keyword.
#
# * Note: When you run the automated tests, the tests will simulate
# the user input. You shouldn't need to enter any input manually.
# If the tests hang when you run them, it probably means your code
# doesn't work correctly, yet.
# FUNCTION DEFINITIONS
def passage_start
puts "\nYou can only go north from here. Where do you want to go?"
gets.chomp
end
def cave_choice
puts "\nYou are in a scary cave."
puts "Which direction would you like to go?"
gets.chomp
end
def cave_to_south
puts "\nYou are in a scary passage."
passage_start
end
def cave_to_north
puts "\nYou walk into sunlight."
end
def start
# This loop continues until 'north' is input
# as it is the only permissible direction whilst
# you're in the passage.
while true
choice_1 = passage_start
if choice_1 == "north"
break
# breaks out of this enclosing while loop into the
# outermost while loop, to take you to the cave loop
end
end
end
## MAIN
while true
start
# Cave Loop
while true
choice_2 = cave_choice
if choice_2 == "south"
cave_to_south # Back to the starting passage
elsif choice_2 == "north"
cave_to_north
break
end
end
break
end
puts "\nTHE GAME HAS FINISHED."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment