Python for Game Developers in a Week
Essential Data Structures
Organizing Your Game's Data
Now that you have the basic building blocks of Python, like variables and loops, it's time to organize your game's information. In any game, you need to keep track of a lot of stuff: a player's inventory, character stats, coordinates on a map, or a list of enemies.
Storing each piece of data in its own separate variable would be a nightmare. Instead, we use data structures. These are specialized containers that let you group and manage related data in efficient ways. Let's look at the four most common ones you'll use in Python.
Lists for Ordered Items
Think of a list as a player's backpack or inventory. It's an ordered collection of items, and you can add things to it or take things out. In Python, lists are created with square brackets [].
inventory = ["sword", "health potion", "gold coin"]
print(inventory)
# The player finds a key
inventory.append("key")
print(inventory)
# The player drinks the potion
inventory.remove("health potion")
print(inventory)
Lists are indexed starting from 0. So, to get the first item in the inventory, you'd use inventory[0]. Because you can change them, lists are perfect for things that will update frequently during gameplay.
Tuples for Unchanging Data
A tuple is like a list, but with one crucial difference: you can't change it after you create it. This is called being immutable. Tuples are created with parentheses ().
Why would you want a data structure you can't change? It's useful for data that should remain constant, preventing accidental bugs. For example, the RGB color code for the sky, or a character's fixed starting position on a map.
# RGB color for sky blue
sky_color = (135, 206, 235)
# Starting (x, y) coordinates
start_position = (100, 250)
# You can access items just like a list
print(f"Starting X: {start_position[0]}")
# But trying to change it will cause an error!
# start_position[0] = 50 # This line would crash the program
Use tuples when you want to ensure data stays the same throughout your game's execution. It makes your code safer and more predictable.
Dictionaries for Key-Value Pairs
Imagine a character sheet. You have stats like "Health," "Mana," and "Strength," each with a corresponding value. A dictionary is perfect for this. It stores data in key-value pairs, letting you look up a value using its specific key. Dictionaries are created with curly braces {}.
player_stats = {
"name": "Gideon",
"health": 100,
"mana": 50,
"is_poisoned": False
}
# Access a value by its key
print(f"Health: {player_stats['health']}")
# Update a value
player_stats["health"] = 90
print(f"New Health: {player_stats['health']}")
# Add a new key-value pair
player_stats["gold"] = 25
print(player_stats)
Dictionaries are incredibly useful for representing any object with a set of properties, from player characters to enemies and items.
Sets for Unique Items
Finally, we have sets. A set is an unordered collection that only stores unique elements. If you try to add an item that's already in the set, nothing happens. They are also created with curly braces, but they don't have key-value pairs.
This is great for tracking things like unique achievements unlocked or special abilities a player has learned. You don't want duplicates.
# A player learns some magic spells
spells_learned = {"fireball", "heal"}
print(spells_learned)
# They learn fireball again from another scroll...
spells_learned.add("fireball")
print(spells_learned) # Notice 'fireball' only appears once
# They learn a new spell
spells_learned.add("ice bolt")
print(spells_learned)
Sets are also very fast for checking if an item is present. Checking if a player has learned "fireball" is much quicker with a set than with a long list, which can be important for performance in complex games.
Understanding programming concepts such as variables, loops, conditional and data structures is crucial for game development.
Choosing the right data structure for the job makes your code cleaner, more efficient, and easier to debug. Now, let's see if you can identify which structure is best for a few common game scenarios.
You're building a game and need to keep track of a player's inventory, which will change as they pick up or use items. Which data structure is the best fit for this?
Which of the following game data would be best stored as a tuple?
With these four structures, you can manage nearly all of the data your game will need.