Here is how I solved level 9 of Ruby Warrior.
This is it! I’ve made it to the final level of Ruby Warrior. I was actually a little sad it was over… until I found out level 1-9 is beginners. There’s an intermediate section too! (2D navigation) I was so excited I actually jumped up and down. Yes, in real life.
In the past few levels, I’ve been taking out code that wasn’t needed for different levels. Now that I have to put everything together into one, I decided to rethink my setup. The whole string of if else and nested if else loops were getting confusing to read.
First, I drew a flow chart for decisions.
Since the warrior can only do one thing per turn, I decided to make a function called do_something. This do_something function would return a string, for the action function to be called. I would use return on all the lines so that once a condition was true, the function would return the string.
The good thing about this set up is that it clears up all the nested if-else loops. The bad thing is that the logic is more hidden and not as explicit as previous setups. In each line for do_something, a condition is checked. If that condition returns true, the function returns a string and exits. If that condition is false, the next line of code is run. Essentially, this setup recreates my decision flow chart.
Something a bit different is the clear_shot() function. This function determines whether the warrior has a clear shot of an enemy. It does this by looking ahead 4 spaces, the look method returns an array of 4 elements. The distance of the squares ranges from 0 to 3 (the indices of the array). I use the index function on the array to get the index of the first element that returns true for the specified code block. If none of the spaces return true for .enemy? then I just assign a distance of 4 (assuming the enemy is outside of range). We have to do this otherwise the distance will be nil and we cannot compare nil.
I do the same thing to get the captive distance. Then I compare the captive distance and enemy distance. If the enemy distance is shorter, I know that I have a clear shot of the enemy. We only want the warrior to shoot if he has a clear shot and is not under attack.
After running this code, I realized the warrior does not need to flee from anyone. The warrior gets a chance to rest to good health after defeating the sludge and wizard. After turning around, the warrior approaches and gets the first shot at the archer. Then the warrior takes 3 hits from the Archer (-9 points), which is fine because we can set the minimum health points to be 10 (rest if health is less than 10 and not under attack).
BOOM! That was so much fun. Ruby Warrior is a great way to practice some logic and Ruby code. I really enjoyed the graphics and different character abilities.
I look forward to trying out the Intermediate levels.