File under ‘C’ for ‘Compartmentalizing’

One thing I’ve noticed as I’ve been working on the RPG (which I’ve tentatively been calling “Arena Fighter”), is that the game was getting rather large; it was up to several hundred lines at one point. So I decided it would be a good time to separate it into different files. Doing so obviously helped to make things a bit more abstracted, but it also just seemed to make sense. Compartmentalizing the game simplified the logic a little bit by keeping related pieces of logic together but easily identifiable because of the way Python handles imports. Now I have 11 total files.

For example, I separated the Character class into a file of its own, that way whenever I needed it, I just import character, then any methods are character.method. On top of that I built the file, which basially instantiates the character module and uses it to add a few items to the player’s inventory. Here’s the code from

[sourcecode language=”Python”]
import character
import equipmentlist

global available_items
available_items={1:equipmentlist.dagger, 2:equipmentlist.shortsword, 3:equipmentlist.longsword, 4:equipmentlist.lightarmor, 5:equipmentlist.heavyarmor}

playerone=character.Player("Charles", 1)

The “.add” and “.equip” are methods defined in, with pretty self-explanatory names. But because is where the player’s character is instantiated, when the player buys something from the store, you have to call “player.playerone.add(item)” within the store module. That adds it to the global variable “equipment,” defined in the module, keeping the item accessible from any other module. To run the game, all you do is run “python” in the directory containing all the files. That file just calls “menus.main()” to bring up the main menu, which allows access to menus in the store, the change_equipment menu, and the arena.

Pretty handy stuff, I’d say. Separating things out into modules really makes for *much* cleaner code.