Jeu de culture optimisé

Description

Bonjour à tous,
ceci est une réécriture totale de la source de Sliven, "Jeu de culture", afin qu'il puisse s'en inspirer pour améliorer son code et ses prochains codes.

Voici ce que j'ai fait :
- transformation de la majorité des chaînes en constantes, ce qui permet de faire des boucles plutôt que de tout écrire à la suite (donc on évite la redondance du code)
- correction du franglais atroce
- quelques changements au niveau des explications car c'était pas très intuitif avant
- rajouts des commentaires dans le code - c'est important !
- d'autres petits trucs

Résultat : le code de Sliven faisait 200 lignes "brutes", mon code fait exactement la même chose et fait 100 lignes hors commentaires, dont 50 lignes de constantes et 50 lignes de code.

Source / Exemple :


program CultureGame;

{$APPTYPE CONSOLE}

uses
  SysUtils;

const
 // Les questions
 QUESTIONS: array [0..9] of String = (
 'What is the thing that doesn''t get wet when it enters water?',
 'What is the capital of Sweden?',
 'Which is the heaviest: a kilo of iron or a kilo of paper?',
 'What is the the programming type that can is represented by True or False?',
 'What is the film that made the biggest budget in the world?',
 'Who is the physician who invented relativity theory:  Einstein, Bill Gates or Pythagore?',
 'What shape does the earth have ? Circle, Ellipse, or none of these?',
 'What is the origin of the nazist war leader?',
 'What is the unit that caracterizes screen resolutions?',
 'How many times does one find the number 9 in the digits of the numbers between 5 and 100?');

 // Les explications détaillées
 DETAILED: array [0..9] of String = (
 'I don''t think any of you have ever seen a shadow get wet, so the answer is shadow.',
 'Stockholm is the capital of Sweden with 4253483 inhabitants, and is the biggest Swedish city. It is partly built on several islands.',
 'They weigh the same, of course, because one kilo is one kilo !',
 'The boolean type is named after his inventor, Boole, and is the smallest amount of information that can be represented.',
 'The budget of this movie has reached $3 000 000 and is the biggest budget up to date.',
 'Relativity theory was invented by the great physician, Albert Einstein, in 1915. It unifies special relativity and Newton''s universal gravitation law, and describes gravity as a geometric property of space and time.',
 'Believe it or not, our planet is not a perfect circle, but an ellipse.',
 'Hitler was born in Austria, and not in Germany according to general belief.',
 'Screen resolutions are caracterized by their size in pixels. The greater the number of pixels, the higher the resolution.',
 'Between 5 and 100, there are exactly 20 numbers that contain the digit 9 in one of their digits. The first numbers are 9, 19, 29, 39, ...');

 // Les réponses possibles de l'utilisateur
 USERANSWERS: array [0..9, 0..1] of String = (
 ('OMBRE', 'SHADOW'), ('STOCKHOLM', 'STOCKHOLM'), ('IRON', 'PAPER'), ('BOOLEAN', 'BOOLEAN'),
 ('AVATAR', 'AVATAR'), ('EINSTEIN', 'EINSTEIN'), ('ELLIPSE', 'ELLIPSE'), ('AUSTRIA', 'AUSTRIAN'),
 ('PIXEL', 'PIXEL'), ('20', '20'));

 // True si les réponses données doivent correspondre à USERANSWERS, False si elles ne le doivent pas
 USERMOD: array [0..9] of Boolean = (True, True, False, True, True, True, True, True, True, True);

 // Les résultats selon le score
 SCORERESULTS: array [0..4] of String = (
 'You are terrible, you need to work on your cultural knowledge. Your score is %d%s',
 'Not bad, your IQ score is %d%s, but you can improve.',
 'Good, your IQ score is %d%s',
 'Excellent, your IQ score is %d%s, you are intelligent.',
 'Perfect ! You are a genius, and your IQ score is %d%s');

resourcestring
 // Quelques chaînes utiles
 CORRECT_ANSWER = '***** True *****';
 WRONG_ANSWER   = '***** False *****';
 ENDTEST = 'You finished the test, press <ENTER> to see your IQ score.';
 TITLE = 'Answer these questions to know your IQ score.';
 ENDPROG = '******* Thanks for playing this game *******';
 ENDPROG2 = 'It is not related in any way with IQ score or intelligence tests, apart from the last question.';

Var
 I, Score: Longword;
 Ans: String;

// Vérifie la réponse de l'utilisateur, dans Ans, à la question I
function CheckAnswer: Boolean;
begin
 // Formule logique : prend en compte les deux possibilités de réponse et le modificateur
 Result := ((Uppercase(Ans) = USERANSWERS[I, 0]) or (Uppercase(Ans) = USERANSWERS[I, 1]) = USERMOD[I]);
end;

begin
 // initialisation
 Score := 0;

 // pour chaque question ...
 for I := 0 to 9 do
  begin
   // on pose la question
   WriteLn(QUESTIONS[I]);
   // on récupère la réponse de l'utilisateur
   ReadLn(Ans);
   // on vérifie la réponse
   if CheckAnswer then
    begin
     // si elle est correcte, on augmente le score et on dit qu'elle est correcte
     Inc(Score);
     WriteLn(CORRECT_ANSWER);
    end else WriteLn(WRONG_ANSWER); // sinon bah elle est fausse quoi

   WriteLn('');
  end;

 // fin du test
 Writeln('*****************************');
 WriteLn('');
 WriteLn(ENDTEST);
 WriteLn('');

 // on donne le résultat du test selon le score
 case Score of
  0..2: WriteLn(Format(SCORERESULTS[0], [Score * 10, '%']));
  3..5: WriteLn(Format(SCORERESULTS[1], [Score * 10, '%']));
  6..8: WriteLn(Format(SCORERESULTS[2], [Score * 10, '%']));
     9: WriteLn(Format(SCORERESULTS[3], [Score * 10, '%']));
    10: WriteLn(Format(SCORERESULTS[4], [Score * 10, '%']));
 end;

 // on va donner les explications
 WriteLn('');
 Writeln('*****************************');
 WriteLn('');
 WriteLn('Please hit <ENTER> to know the answers.');
 WriteLn('');
 ReadLn;
 WriteLn('Answers :');
 WriteLn('');

 // pour chaque question
 for I := 0 to 9 do
  begin
   // on donne les explications détaillées de cette question
   WriteLn(Format('Answer to question %d', [I]));
   WriteLn('');
   WriteLn(Format('[%d] %s', [I, DETAILED[I]]));
   WriteLn('');
  end;

 // fin du test : appuyez sur entrée pour quitter
 Writeln(ENDPROG);
 WriteLn(ENDPROG2);
 ReadLn;
end.

Conclusion :


Bien sûr, l'idée n'est pas de moi, il s'agit juste d'une optimisation afin de venir en aide à un membre, mais vous pouvez bien sûr commenter les techniques utilisées. Je me base fortement sur les constantes et il y a sûrement mieux à faire. D'autant plus que certaines méthodes utilisées dans mon code peuvent sembler mystérieuses.

Cordialement, Bacterius !

PS : Codé sous Delphi 6 PE.

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.