Here is my work for Exercise 35.
1. Draw a map of the game and how you flow through it.
2. Fix all of your mistakes, including spelling mistakes.
Fixed line 30, change “>” to “> “.
3. Write comments for the functions you do not understand.
4. Add more to the game. What can you do to both simplify and expand it?
You can add another room, or add options for each room.
I added an option so that the greedy person has one last chance to put some gold back! If they put some back, they win. If not, they lose.
5. The gold_room has a weird way of getting you to type a number. What are all the bugs in this way of doing it? Can you make it better than what I’ve written? Look at how =~ works for clues.
The gold room checks if you typed a number by checking to see if the entered input contains a “0” or “1” in the string. This is problematic because not all numbers contain “0” or “1”. For example, if the user typed 32, they would get “Man, learn to type a number!” I changed the code by first using the .to_i method on the string, then checking to see if the result is a numeric. (In my screenshot code at the very top of this post.)
However, I realized that does not work. Say the user entered “A”. “A” converted to an integer is 0, which is a numeric! Another way is to check if the string converted to an integer and then converted back to a string is the same as the original string.
In the case of “30”, it would be converted to 30 (an integer) then back to “30” a string. This is the same as the original string. In the case of “f”, it would be converted to the integer 0 then to “0” a string. This would return false since it is not the same as the original string.
To also allow floating point numbers, we can add || choice.to_f.to_s == choice to the condition. However, the floating point will be preserved as in the code block we convert choice to an integer. So if the user entered “3.3”, this would be converted to the integer 3.
Another solution I found is to use regexp with the =~ match operator:
choice =~ /\A[-+]?[0-9]*\.?[0-9]+\Z/
It is surprising that something you would expect to be easy like “check if the input is a number” can be more complicated once you consider the possible input values. Also, when giving possibilities (‘flee’ or ‘eat head’ in the Cthulhu room for example), it is hard to guess what the user will type. Do you want their input to match your string exactly, or will you accept input that includes certain strings?
This was a fun exercise to go through, using comparison operators and user input, we can create an adventure game that is interactive! Each room in this exercise is defined by a method which we call depending on the evaluation of boolean expressions.
I learned about exit(), the exit method. The exit method exits the program and returns a status of true, indicating success.