In our last issue, we explained how to use Python to create a writing “game” (see link to article under Learn More). Using Python’s random module, players could “roll” to randomly select a genre (either Mystery or Horror) and story elements (characters, setting and plot) to base their creative short stories on. We can make this program more complex yet concise by using OOP – Object Oriented Programming.
If you look at both programs (linked below under Learn More), you will notice the OOP version is shorter than the original version and looks quite different.
One of the first things you may notice is how genres are selected. In the original Roll a Story program, we used a dictionary to randomly select genres assigned to numbers. In the OOP version, we created a class, StoryOptions, and a method, get_genre, to randomly select a genre. We were able to get rid of all the messy and lengthy dictionaries and replace them with objects and methods to randomly select characters, settings and plots.
Additionally, because we are using one class, we can easily add in additional options to the game to make it more interesting. This is most evident when looking at the new options available for setting and plot. Let’s look at the two programs to see how that was done.
Notice in the original version how settings were randomly selected using a dictionary. After the genre is randomly selected, randomly selected settings were chosen based on whether a number 1, 2 or 3 was selected. Notably, there wasn’t a way included for different settings based on the character chosen. For the purposes of the game, this didn’t make sense. For example, if the selected character is a thief, the setting of Area 51 wouldn’t match the storyline!
The same thing occurred with plot in the original version. After the character and setting were randomly selected, the game rolled again for a plot. The options are static and may or may not make sense based on the outcome. For example, you may roll an FBI Agent character, Area 51 setting and a plot of “The Principal goes missing”. That would make for an odd and quite uninspiring story!
The new version of the game using OOP allows the randomly chosen options to flow better together. Looking at the StoryOptions class, there is a method called get_setting. This method uses conditional statements to randomly assign an appropriate setting that makes sense based on the character that was also randomly chosen. Now for example, if the user randomly gets an FBI Agent, their randomly selected settings will consist of settings that make sense for a FBI Agent, including The White House, Capitol Hill, and Washington Monument. The same strategy is used for the randomly selected plots. By using classes, methods and conditional statements, the options for plots makes sense!
By utilizing OOP, the game is more structurally sound, provides fun storyline alternatives and allows for a way to easily include additional options for players.