Dungeon Coder


Stacking Enchantments

An Introduction to the Stack Data Structure

Even the most well-made armor could use a little boost. Many adventurers find themselves in villages containing one or more individuals skilled in the art of enchantment. If you're on an adventure and you've got the necessary gold, you should get your armor enchanted. Hey, if you've got more than enough gold, you might even want to apply more than one enchantment on your armor. This is often called "stacking enchantments".

We'll come back to our analogy in a moment. First, a little bit on the stack data structure. The stack data structure is a first in, last out (FILO) data structure. That is, when data is added to a stack, it is placed on the top of the stack. This is like putting your dishes away. You place one plate on top of the other. Once you're ready to grab a plate and use it, you grab the last plate you had placed on top. So, the last plate to be added is the first plate to be removed. On the other hand, the first plate to be put away will be the last to be removed (first in, last out).

What does this have to do with stacking enchantments? Imagine that each additional enchantment is placed on top of the previous one. If that is the case, then if you decide to remove an enchantment, you'll have to remove the one that was added last. If you want to remove the first enchantment that was added, you'll have to remove every other enchantment that had been added on top of it first.

Okay, let's see some code.

Run the code. Change some things here and there. If things get messy, you should be able to refresh the page to get the original code back.

Assignment:


  1. Add a for loop to the above code that pushes at least 5 more enchantments onto the stack.
  2. Create a new stack object called userEnchant.
  3. Write a while loop that prompts a user to enter the name of an enchantment. The loop should then push it to the userEnchant stack, and then ask the user if they want to add another enchantment. If the user enters 'yes', then you should ask them what enchantment they want to add, then push that enchantment. If no, then you should break from the loop.
  4. Add the option for the user to remove an enchantment from the userEnchant stack. If the user says yes, you should pop from the stack. If the user says no, your loop should break.
  5. Look up the "del" keyword in python. Based on your research, add the necessary lines to remove both the enchantments and userEnchant objects at the end of your code.

Join the Dungeon Crawl: A place for programmers to ponder, partake, and peruse postulations pertaining to programming, politics, potions, and pizza.

If you subscribe on Patreon, you will be granted access to the Dojo, a growing collection of quality computer science classes created and actively mantained and frequented by the Dungeon Master!

Become a Patron!

Glossary

Contact: dungeon_master@dungeoncoder.com