Do you need to populate a fantasy town in a hurry? Let’s create some NPCs!
We’ll be learning about lists, loops, and conditionals to generate NPCs. By the end of this tutorial, you should be able to create NPCs from custom lists of traits.
Creating a List
When learning to roll for initiative, we stored individual numbers or strings in variables. We can also save data in something called a “List” in Python. We can store strings, numbers, or even lists within lists! However, we’ll keep it simple to start.
We create the list by giving it a name, using the assignment operator (“=”), and putting data in-between square brackets. Let’s start by creating an empty list called “hair_color”.
hair_color = []
An empty list may not seem useful now, but you can add items to lists. This is extremely useful as you begin creating more complex programs. To add hair colors to the list, we can do this in two ways:
- Manually type in the values separated by commas
- Use the .append() method to add the value to the end of the list
hair_color = ["blonde", "black", "red"]
hair_color.append("brown")
If we print hair_color to the console, we will see the following:
[‘blonde’, ‘black’, ‘red’, ‘brown’]
The .append() method allows us to update the list at any time.
A List of Lists
Hair color won’t be enough to make a detailed character. Let’s make a list of occupations and personality traits:
hair_color = ["blonde", "black", "brown", "gray", "red"]
occupation = ["teacher", "blacksmith", "alchemist", "shopkeeper", "guard", "rat catcher"]
personality_traits = ["abrasive", "cautious", "detached", "easygoing", "jolly", "inattentive", "suspicious"]
From here, we can create a list of all of these lists called, “master_list” by doing the following:
master_list = [hair_color, occupation, personality_traits]
Next, we’ll learn how to iterate through our lists to generate some random NPCs!