2525
2626import requests
2727import validators
28- import unicodedata
28+ import jsonschema
29+ from jsonschema .validators import validate
2930
3031class bcolors :
3132 HEADER = '\033 [95m'
@@ -43,65 +44,55 @@ def printerr(msg):
4344
4445
4546class Question :
46- def __init__ (self , titre , choix , bonne_reponse ):
47- self .titre = titre
48- self .choix = choix
49- self .bonne_reponse = bonne_reponse
50-
51- def FromData (data ):
52- # Question : Titre, Choix, Bonne Reponse
53- # From Data : Choix, Bonne Reponse, Titre
54- q = Question (data [2 ], data [0 ], data [1 ])
55- return q
47+ def __init__ (self , title , choice , is_answer ):
48+ self .title = title
49+ self .choice = choice
50+ self .is_answer = is_answer
5651
5752 def FromJSON (json_question ):
5853 # Question : Titre, Choix, Bonne Reponse
5954 # From JSON Question : Titre, Choix[4]:[Reponse_1,True],[Reponse_2,False],[Reponse_3,False],[Reponse_4,False]
60- bonne_reponse = None
61- choix = []
55+ is_answer = None
56+ choice = []
6257 for i in range (0 , len (json_question ['choix' ])):
63- choix .append (json_question ['choix' ][i ][0 ])
58+ choice .append (json_question ['choix' ][i ][0 ])
6459 if json_question ['choix' ][i ][1 ]== True :
65- bonne_reponse = json_question ['choix' ][i ][0 ]
66- return Question (json_question ['titre' ], choix , bonne_reponse )
60+ # Enregistre le numero de la bonne reponse
61+ # is_answer = json_question['choix'][i][0]
62+ is_answer = i
63+ return Question (json_question ['titre' ], choice , is_answer )
6764
68- def poser (self , index ):
65+ def ask (self , index ):
6966 print (f"QUESTION { index } " )
70- print (" " + self .titre )
71- for i in range (len (self .choix )):
72- print (" " , i + 1 , "-" , self .choix [i ])
73-
74- print ()
75- resultat_response_correcte = False
76- reponse_int = Question .demander_reponse_numerique_utlisateur (1 , len (self .choix ))
77- if self .choix [reponse_int - 1 ].lower () == self .bonne_reponse .lower ():
78- print ("Bonne réponse" )
79- resultat_response_correcte = True
67+ print (" " + self .title )
68+ for i in range (len (self .choice )):
69+ print (" " , i + 1 , "-" , self .choice [i ]+ "\n " )
70+
71+ if Question .request_choice_to_user (1 , len (self .choix )) == self .is_answer :
72+ print ("Bonne réponse\n " )
73+ return True
8074 else :
81- print ("Mauvaise réponse" )
82-
83- print ()
84- return resultat_response_correcte
75+ print ("Mauvaise réponse\n " )
76+ return False
8577
86- def demander_reponse_numerique_utlisateur (min , max ):
87- reponse_str = input ("Votre réponse (entre " + str (min ) + " et " + str (max ) + ") :" )
78+ def request_choice_to_user (min , max ):
79+ str_answer = input ("Votre réponse (entre " + str (min ) + " et " + str (max ) + ") :" )
8880 try :
89- reponse_int = int (reponse_str )
90- if min <= reponse_int <= max :
91- return reponse_int
92-
93- print ("ERREUR : Vous devez rentrer un nombre entre" , min , "et" , max )
81+ int_answer = int (str_answer )
82+ if min <= int_answer <= max :
83+ return int_answer
84+ else :
85+ print ("ERREUR : Vous devez rentrer un nombre entre" , min , "et" , max )
9486 except :
9587 print ("ERREUR : Veuillez rentrer uniquement des chiffres" )
96- return Question .demander_reponse_numerique_utlisateur (min , max )
88+ return Question .request_choice_to_user (min , max )
9789
9890class Questionnaire :
9991
10092 schema = {
101- "$schema" : "json_questionnaire" ,
102- "$id" : "https://openquizzdb.org/" ,
93+ "$schema" : "http://json-schema.org/draft/2020-12/schema" ,
10394 "type" : "object" ,
104- "required" : ["titre" , "questions" ],
95+ "required" : [ "titre" , "questions" ],
10596 "properties" : {
10697 "categorie" : {"type" : "string" },
10798 "titre" : {"type" : "string" },
@@ -110,16 +101,16 @@ class Questionnaire:
110101 "default" : [],
111102 "items" : {
112103 "type" : "object" ,
113- "required" : ["titre" , "choix" ],
114104 "properties" : {
115105 "titre" : {"type" : "string" },
116106 "choix" : {
117107 "type" : "array" ,
118- "default" : [],
119108 "minItems" : 2 ,
120109 "items" : {
121110 "type" : "array" ,
122- "default" : []
111+ "minItems" : 2 ,
112+ "prefixItems" : [{"type" : "string" }, {"type" : "boolean" }],
113+ "items" : False
123114 }
124115 }
125116 }
@@ -130,28 +121,25 @@ class Questionnaire:
130121 }
131122
132123 def __init__ (self , json_questionnaire ):
124+ '''Test the expected json schema before to initiate'''
133125
134- # Verification du format questionnaire (categorie et difficulte non bloquant, titre ou questions bloquants)
135- self .categorie = json_questionnaire ['categorie' ] if json_questionnaire .get ('categorie' ) else 'inconnue'
136- self .difficulte = json_questionnaire ['difficulte' ] if json_questionnaire .get ('difficulte' ) else 'inconnue'
137-
138- if not json_questionnaire .get ('titre' ) or not json_questionnaire .get ('questions' ):
139- raise Exception ("JSON_Questionnaire_format_error" )
126+ try
127+ validate (json_questionnaire , self .schema )
128+ except jsonschema .exceptions .ValidationError :
129+ printerr (f"Incompatible Json schema in file : { filename } " )
140130 else :
131+ # 'categorie', 'difficulte' : non-blocking properties, but better to be completed as unknown if absent
132+ self .categorie = json_questionnaire ['categorie' ] if json_questionnaire .get ('categorie' ) else 'inconnue'
133+ self .difficulte = json_questionnaire ['difficulte' ] if json_questionnaire .get ('difficulte' ) else 'inconnue'
134+
135+ # 'titre' or 'questions' : required properties already checked into schema
141136 self .titre = json_questionnaire ['titre' ]
142137 self .questions = []
143138 for json_question in json_questionnaire ['questions' ]:
144139 self .questions .append ( Question .FromJSON (json_question ) )
145140
146- # # Convertit un questionnaire JSON en questions sous format questionnaire
147- # def From_JSON_Questionnaire(self, json_questionnaire):
148- # if json_questionnaire != None :
149- # for json_question in json_questionnaire['questions']:
150- # questions.append( Question.FromJSON(json_question) )
151- # return questions
152-
153- def lancer (self ):
154- # Lancement du questionnaire
141+ def run (self ):
142+ # Launch of the questionnaire
155143 print (f"Catégorie : { self .categorie } " )
156144 print (f"Difficulté : { self .difficulte } " )
157145 print (f"Titre : { self .titre } \n " )
@@ -160,8 +148,9 @@ def lancer(self):
160148 index = 0
161149 for question in self .questions :
162150 index += 1
163- if question .poser (index ):
151+ if question .ask (index ):
164152 score += 1
153+
165154 print ("Score final :" , score , "sur" , len (self .questions ))
166155 return score
167156
@@ -221,8 +210,9 @@ def load_json_argv( sysargv ):
221210def main ():
222211
223212 json_data = load_json_argv ( sys .argv )
224- # if json_data :
225- # Questionnaire(json_data).lancer()
213+
214+ if json_data :
215+ Questionnaire (json_data ).run ()
226216
227217if __name__ == "__main__" :
228218 main ()
0 commit comments