Bonus : Let’s create a quiz !¶
Download the full code
Creating our quiz¶
Of course Tiramisu is great to handle options, but here’s a little thing you can do if you’re just bored and don’t know what to do ;).
First, as always, let’s import everything we need from Tiramisu and create our options :
1 2 3 | from tiramisu import MetaConfig, Config, OptionDescription, BoolOption, ChoiceOption, StrOption, IntOption, Params, ParamOption, default_storage, list_sessions
from tiramisu.error import ValueOptionError
q1 = ChoiceOption('q1', 'Question 1 : What does the cat say ?', ('woof', 'meow'))
|
We have our first question, so now we’re going to define the correct answer in a second option :
1 | a1 = StrOption('a1', 'Answer 1', default='meow', properties=('frozen', ))
|
The answer is frozen so that when it is set, it cannot change. And finally a last option that will verify if the answer is correct :
1 v1 = BoolOption('v1', 'Verif of question 1', callback=verif, callback_params=Params((ParamOption(q1), ParamOption(a1))))
This option will use a callback function that will verify if the answer given by the user (which will become the value of q1) is the same as the correct answer (which is the value of a1). Here is this function (of course you have to declare at the begining of your code, before your options) :
1 2 | def verif(q: str, a: str):
return q == a
|
So here’s what our first question looks like :
1 2 3 | q1 = ChoiceOption('q1', 'Question 1 : What does the cat say ?', ('woof', 'meow'))
a1 = StrOption('a1', 'Answer 1', default='meow', properties=('frozen', ))
v1 = BoolOption('v1', 'Verif of question 1', callback=verif, callback_params=Params((ParamOption(q1), ParamOption(a1))))
|
Let’s add some more questions :
1 2 3 | q2 = ChoiceOption('q2', 'Question 2 : What do you get by mixing blue and yellow ?', ('green', 'red', 'purple'))
a2 = StrOption('a2', 'Answer 2', default='green', properties=('frozen', ))
v2 = BoolOption('v2', 'Verif of question 2', callback=verif, callback_params=Params((ParamOption(q2), ParamOption(a2))))
|
Pretty simple. One more ?
1 2 3 | q3 = ChoiceOption('q3', 'Question 3 : Where is Bryan ?', ('at school', 'in his bedroom', 'in the kitchen'))
a3 = StrOption('a3', 'Answer 3', default='in the kitchen', properties=('frozen', ))
v3 = BoolOption('v3', 'Verif of question 3', callback=verif, callback_params=Params((ParamOption(q3), ParamOption(a3))))
|
Yeah, I don’t think you can understand this one if you’re not french… Let’s add another one.
1 2 3 | q4 = ChoiceOption('q4', 'Question 4 : Which one has 4 legs and 2 wings ?', ('a wyvern', 'a dragon', 'a wyrm', 'a drake'))
a4 = StrOption('a4', 'Answer 4', default='a dragon', properties=('frozen', ))
v4 = BoolOption('v4', 'Verif of question 4', callback=verif, callback_params=Params((ParamOption(q4), ParamOption(a4))))
|
Did you know that ? A dragon has 4 legs and 2 wings, a wyvern has 2 back legs and 2 wings, a drake has 4 legs and no wings, and a wyrm has no legs nor wings(it’s like some sort of snake-dragon). Anyway, let’s add a last one.
1 2 3 | q5 = ChoiceOption('q5', 'Question 5 : Why life ?', ('because', 'I don\'t know', 'good question'))
a5 = StrOption('a5', 'Answer 5', default='good question', properties=('frozen', ))
v5 = BoolOption('v5', 'Verif of question 5', callback=verif, callback_params=Params((ParamOption(q5), ParamOption(a5))))
|
Well that escalated quickly… At least we’re done with our questions. Let’s just create one last option.
1 | res = IntOption('res', 'Quiz results', callback=results, callback_params=Params((ParamOption(v1), ParamOption(v2), ParamOption(v3), ParamOption(v4), ParamOption(v5))))
|
This option will use a callback function to count how many correct answers the user has given. Here’s this function :
1 2 3 4 5 6 7 | def results(v1:bool, v2: bool, v3: bool, v4: bool, v5: bool):
verif = (v1, v2,v3, v4, v5)
correct=0
for v in verif:
if v == True:
correct += 1
return correct
|
Now we just have to create our OptionDescription and Config (well it’s a MetaConfig here, but we’ll see this later)…
1 2 3 4 5 6 7 | rootod = OptionDescription('root', '', [q1, q2, q3, q4, q5, a1, a2, a3, a4, a5, v1, v2, v3, v4, v5, res])
default_storage.setting(engine="sqlite3")
meta_cfg = MetaConfig([], optiondescription=rootod, persistent=True, session_id="quiz")
for session_id in list_sessions():
# our meta config is just here to be a base, so we don't want its session id to be used
if session_id != "quiz":
meta_cfg.config.new(session_id, persistent=True)
|
… and add some loops to run our quiz !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | def run_quiz(meta_cfg: MetaConfig):
pseudo = input("Enter a name :")
cfg = meta_cfg.config.new(pseudo, persistent=True)
cfg.property.read_write()
nb_q = (len(list(cfg.option.list())) - 1) // 3 + 1
for qno in range(1, nb_q):
q = 'q' + str(qno)
a = 'a' + str(qno)
v = 'v' + str(qno)
print(cfg.option(q).information.get('doc'))
print(*cfg.option(q).value.list(), sep=" | ")
while True:
input_ans = input('Your answer : ')
try:
cfg.option(q).value.set(input_ans)
except ValueOptionError as err:
print(err)
else:
break
print('')
if cfg.option(v).value.get() is True:
print("Correct answer !")
print('')
else:
print("Wrong answer...")
print("The correct answer was : ", cfg.option(a).value.get())
print('')
print("Correct answers : ", cfg.option('res').value.get(), " out of ", qno)
if cfg.option('res').value.get() == 0 :
print("Ouch... Maybe next time ?")
elif cfg.option('res').value.get() == qno :
print("Wow, great job !")
print("==============================================")
|
Now let’s play !
Enter a name :DocMaster
Question 1 : What does the cat say ?
woof | meow
Your answer : meow
Correct answer !
Question 2 : What do you get by mixing blue and yellow ?
green | red | purple
Your answer : green
Correct answer !
Question 3 : Where is Bryan ?
at school | in his bedroom | in the kitchen
Your answer : in the kitchen
Correct answer !
Question 4 : Which one has 4 legs and 2 wings ?
a wyvern | a dragon | a wyrm | a drake
Your answer : a dragon
Correct answer !
Question 5 : Why life ?
because | I don't know | good question
Your answer : good question
Correct answer !
Correct answers : 5 out of 5
Wow, great job !
==============================================
Hey, that was easy ! Almost like I already knew the answers… Oh wait…
Get players results¶
Now that you have your quiz, you can play with friends ! And what’s better than playing with friends ? Crushing them by comparing your scores of course ! You may have noticed that the previous code had some storage instructions. Now we can create a score board that will give each player’s latest score with their errors !
We created a meta config that will be used as a base for all configs we will create : each time a new player name will be entered, a new config will be created, with the new player’s name as it’s session id. This way, we can see every player’s result !
So, earlier, we created a MetaConfig, and set the storage on sqlite3, so our data will not be deleted after the quiz stops to run.
1 2 3 4 res = IntOption('res', 'Quiz results', callback=results, callback_params=Params((ParamOption(v1), ParamOption(v2), ParamOption(v3), ParamOption(v4), ParamOption(v5)))) rootod = OptionDescription('root', '', [q1, q2, q3, q4, q5, a1, a2, a3, a4, a5, v1, v2, v3, v4, v5, res]) default_storage.setting(engine="sqlite3") meta_cfg = MetaConfig([], optiondescription=rootod, persistent=True, session_id="quiz")
The config are not linked to their metaconfig, so we have to rebuild them :
1 2 3 4 for session_id in list_sessions(): # our meta config is just here to be a base, so we don't want its session id to be used if session_id != "quiz": meta_cfg.config.new(session_id, persistent=True)
When the quiz runs, we will create a new Config in our MetaConfig :
1 2 3 4 def run_quiz(meta_cfg: MetaConfig): pseudo = input("Enter a name :") cfg = meta_cfg.config.new(pseudo, persistent=True) cfg.property.read_write()
Now we will create another function that will print each player’s results. This function will read each Config in our MetaConfig and give the scores for each question, plus each player’s final score :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 def quiz_results(meta_cfg: MetaConfig): for cfg in meta_cfg.config.list(): print("==============================================") print(cfg.config.name()) print("") nb_q = (len(list(cfg.option.list())) - 1) // 3 + 1 for qno in range(1, nb_q): q = 'q' + str(qno) v = 'v' + str(qno) print("Question ", qno, " :") if (cfg.option(v).value.get()) is True: print("Correct answer.") else: print("Wrong answer :", cfg.option(q).value.get()) print("") print(cfg.config.name(), "'s score : ", cfg.option("res").value.get(), "out of ", qno)
Here’s what we get :
DocMaster Question 1 : Correct answer. Question 2 : Correct answer. Question 3 : Correct answer. Question 4 : Correct answer. Question 5 : Correct answer. DocMaster 's score : 5 out of 5
You’ve got everything now, so it’s your turn to create your own questions and play with your friends !