“Welcome, welcome, one and all! The show's about to start. I'm the Hogwarts Sorting Hat and it's time to play my part. You may call me worn and ragged if that's all you truly see…But listen close and I will tell where you're supposed to be! Go ahead and try me on! There's nothing left to fear. I'll find right where you belong by looking between your ears.”
This is a quote from the Sorting Hat in the magical wizarding world of Hogwarts, where Harry, Hermione, and Ron went on so many adventures and quests, fighting against enemies, and forging lifelong friendships. Today, we will enter this world of magic too, by learning how to code a game in Python – specifically how to create a Sorting Hat!
As the Sorting Hat says, don’t fear. You can do this using simple Python commands. And of course for those of you eager for a challenge, secretly hidden in the code are functions to inspire you to create your own animations – or should we rather say, create your own magic!
Discover how to code a game in Python
Let’s start! Today, we will use basic concepts in Python starting from importing packages, interacting with the user using input(), and ending with taking decisions using if-elif-else structures. Simply use this template: template and follow along! At the end of this tutorial, you should have a Sorting Hat, just like this! → Sorting Hat Game & Code for Sorting Hat
For live expert instruction making cool Python games, join our award-winning Python for AI classes!
Intro. Import, import!
Coding is a collaborative process. You might one day build awesome games by working together with your friends, or even help work towards a cure for a disease by working with a mix of scientists, researchers, and coders! So the first skill to tackle is importing code, so you can use awesome commands that are simply waiting for you to use.
In this project, we want to import all the functions available from the turtle package (a drawing tool, great for animations). We also want to borrow all the code from the friendly helper.py file which is aptly named (it is your helper!). Finally, we wish to import the random package, and the time package, so we can use specific tools later on. Simply see the commands below.
P.S. The * stands for everything. For example, the code highlighted below means, from the helper.py file, import all the code!
1. Let the Hogwarts Sorting Hat speak!
Inside the helper.py file, there is a function called setup(). Can you find it?
Now, scroll all the way down until you see the end of the function (Psst, remember, we know that a function is over, if the indentation stops! In other words, we see code that is indented outside of the function block.
Now, how many objects does this function return? Hmmm… spoiler alert, it is two!
One, it will return to us a Turtle object we can use to draw shapes and move around the screen to write text or show images! Two, it returns a Screen object, which you can simply think of, as a special key to a Python universe portal that allows you to control the Screen – things like the color, the size.
Let’s now use this function, and store the two outputs! Run the code below (or should we say Aparecium!) What appears?
2. Colors! What’s your favorite?
Each of the 4 Hogwarts Houses have their own special colors to represent them. Gryffindor - red and gold, Slytherin - green and silver, Hufflepuff - black and yellow, and Ravenclaw - blue and bronze.
What we will do then, is ask someone which of these color combinations they would prefer, if they had to choose what robe to wear to Hogwarts! Then, we will store their answer. All we need is print() and input().
Recall, that anything inside the print() statement should be a String. In other words, make sure you convert numbers to a String using str(), and put all else inside quotation marks! input() is awesome as it allows us to interact with the user, whoever playing this game. Simply, make sure, just like in print(), to pass in a String as input, and to store the user’s typed answer in a variable.
(P.S. If you want an extra challenge, make sure to check if someone types in complete nonsense, and prevent that from being allowed!)
3. Personality Traits - What are your strengths?
Now, we next want to ask the user to share which personality traits they feel best describe them. Do you remember that every Hogwarts House reflects different types of strengths? Here is a quote from the Sorting Hat!
“By Gryffindor, the bravest were prized far beyond the rest; For Ravenclaw, the cleverest would always be the best; For Hufflepuff, hard workers were most worthy of admission; And power-hungry Slytherin loved those of great ambition.”
So let’s ask them to choose between different strengths! Very similar to Step 3, use print() and input() to ask the user what they would choose best describes them. Remember, if you expect the user to give you a number, then make sure to convert the String output from input() into an integer, or a float using int() or float().
4. Time for decision making!
The easy way to sort someone into a Hogwarts House, is if they are let’s say a ‘perfect’ match. For this, we will create a list to store both the user’s answers: color, and personality traits.
Now there’s also the scenario of them not easily fitting into one House easily…but that’s okay! We mean, rumor holds that Harry Potter himself could have fit into Slytherin!
Harry Potter: "Not Slytherin, not Slytherin."
Sorting Hat: "Not Slytherin, eh? Are you sure? You could be great, you know, it’s all here in your head, and Slytherin will help you on the way to greatness, no doubt about that — no? Well, if you’re sure — better be GRYFFINDOR!"
So in this scenario, what we will have to do is choose one of the houses randomly! For this, we will create a dictionary that assigns the numbers 1-4 to each Hogwarts House (not in any particular order).
5. If-elif-else save the day!
Okay, now it’s the proud moment of the Sorting Hat. Taking the important decision!
If someone is a ‘perfect fit’ for one of the Hogwarts Houses above, using the color and personality traits, easy! We can use a series of if-elif-else statements to print out their House using print(). Just for extra fun, we can also reset the screen (to build up suspense of course) using t.reset(), and also show them a cool animation using their house’s mascot! The functions we can use are: draw_gryffindor(), draw_slytherin(), draw_hufflepuff(), and draw_ravenclaw(), all of which are from helper.py, and take Turtle and Screen objects from the Intro step above, as input.
However, if the user is not a perfect fit, we want to randomly choose a number between 1-4 using random.randint()! Then, we want to access the House value stored in the dictionary we made earlier, using this number as the key. All done! We then simply repeat the steps above, so the user has a nice message, and animations as well.
If you prefer to watch instructions, follow our video tutorial:
Code a Hogwarts sorting hat game in Python
Now, run your code, and enjoy what you have created! Which Hogwarts House do you fit in? Hope you enjoyed this tutorial, and if you want more games check out Python games for kids. If you want to learn more Python, we would love to welcome you to our live online, expert-led Python for AI class, here at Create & Learn. There's even a free Python class, so there's no risk in trying!
Written by Pavithra Nagarajan, a Create & Learn instructor. Pavithra is a bioinformatician and completed her master's degree from Harvard T.H. Chan School of Public Health. She finds computational biology awesome (code-ception she wishes it were called), and is the curriculum designer for these classes here at Create & Learn. She truly loves teaching, and is a dancer.