Juego de la consola Hangman -- ++ campo con hangman camp codereview Relacionados El problema

Console HangMan game


2
vote

problema

Español
  #include <iostream> #include <string> #include <algorithm> #include <time.h> int faults = 0; int hangman();  int i = hangman(); int main(){   srand(time(NULL)); while (i == 1){     std::string words[7]{"Alpha", "Cornwall", "Crepuscular", "Blind", "Steroid", "Plunder", "Talisman"};     std::string word = words[rand() % 7];     int n;      n = rand() % word.length();     char underscore = '_';     char checkAnswer = word.at(n);     word.at(n) = underscore;      std::cout << word;     char answer;     std::cin >> answer;       if (answer == checkAnswer){         std::cout << "Correct!";     }     else{         faults++;         hangman();     } }       }       int hangman(){        if (faults == 0){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|" << std::endl;         std::cout << "|" << std::endl;     std::cout << "|" << std::endl;     return 1; } else if (faults == 1){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|" << std::endl;     std::cout<<"|" << std::endl;     return 1; } else if (faults == 2){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |"<<std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|" << std::endl;         ;     return 1; }  else if (faults == 3){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                     /" << std::endl;         ;     return 1; } else if (faults == 4){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      X" << std::endl;     return 1; } else if (faults == 5){     std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      X" << std::endl;         std::cout << "                       -" << std::endl;     return 1; } else if (faults == 6){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      X" << std::endl;     std::cout << "                      - -" << std::endl;     return 1; } else if (faults == 7){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      X" << std::endl;     std::cout << "                      - -" << std::endl;     std::cout << "Dead.Dead.The hangman is dead!You lose!" << std::endl;     return 0; } }   
Original en ingles
#include <iostream> #include <string> #include <algorithm> #include <time.h> int faults = 0; int hangman();  int i = hangman(); int main(){   srand(time(NULL)); while (i == 1){     std::string words[7]{"Alpha", "Cornwall", "Crepuscular", "Blind", "Steroid", "Plunder", "Talisman"};     std::string word = words[rand() % 7];     int n;      n = rand() % word.length();     char underscore = '_';     char checkAnswer = word.at(n);     word.at(n) = underscore;      std::cout << word;     char answer;     std::cin >> answer;       if (answer == checkAnswer){         std::cout << "Correct!";     }     else{         faults++;         hangman();     } }       }       int hangman(){        if (faults == 0){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|" << std::endl;         std::cout << "|" << std::endl;     std::cout << "|" << std::endl;     return 1; } else if (faults == 1){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|" << std::endl;     std::cout<<"|" << std::endl;     return 1; } else if (faults == 2){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |"<<std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|" << std::endl;         ;     return 1; }  else if (faults == 3){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                     /" << std::endl;         ;     return 1; } else if (faults == 4){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      X" << std::endl;     return 1; } else if (faults == 5){     std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      X" << std::endl;         std::cout << "                       -" << std::endl;     return 1; } else if (faults == 6){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      X" << std::endl;     std::cout << "                      - -" << std::endl;     return 1; } else if (faults == 7){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      O" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|                      X" << std::endl;     std::cout << "                      - -" << std::endl;     std::cout << "Dead.Dead.The hangman is dead!You lose!" << std::endl;     return 0; } } 
     
 
 

Lista de respuestas

6
 
vote

En primer lugar, no es así como se implica la Hangman, pero no lo cuestionaré, solo revisaré su código.

1. Asegúrese de que su código realmente funcione

Actualmente tienes un interminable mientras hace un bucle. Su función Hangman () no hace lo que se supone que debe, no actualiza el valor de i. Retire la variable 'I' por completo y cambie el bucle principal a "mientras (Hangman ()) {...}". También debe eliminar la llamada Hangman () al final de su bucle WHILE (en el bloque 'else'), ya que no es necesario después de este ajuste.

(Nota: Eso es lo menos que debes hacer. Le sugiero que eviten completamente las variables globales (todavía tendrás una variable global "), pero cambiar eso requeriría rediseñar el código completo. Deberías al menos cambiar 'Fallas' a 'g_faults' para indicar que es una variable global)

2. Ajuste la salida de su programa

Esta es una especie de Nitpick menor, pero su salida se ve fea. ¿Un espacio antes de la entrada del usuario y una nueva línea después de 'correcta!' debe arreglarlo.

3. Indenta adecuadamente su código

Su código como actualmente es difícil de leer y comprender, ya que no sigue las reglas de identificación comunes. Publicaré su código con una indentación adecuada más tarde.

4. No use la macro nula

Especialmente en esta situación, no hay necesidad de hacerlo (corrígeme si me equivoco). Simplemente escriba el tiempo (0) '.

5. Nombra sus variables correctamente

El nombre de su variable debe aclarar lo que hace la variable. Por lo tanto, su cadena de 'palabra' debe ser 'Current_Word' o al menos 'CWORD', el carácter 'CheckSwer' debe ser 'CANTETTERTTER' o 'FINILIRTE FELIZ' ECT.

sorta código fijo

  #include <iostream> #include <string> #include <algorithm> #include <time.h>  int faults = 0; int hangman();  // No need for 'i' variable  int main(){     // No need for NULL macro     srand(time(0));      // If you declare words[] inside the while loop, it gets created and destroyed every time the loop     // executes. There is no need for that, thus you should declare the array outside of the loop     std::string words[7]{"Alpha", "Cornwall", "Crepuscular", "Blind", "Steroid", "Plunder", "Talisman"};      while (hangman()){         std::string word = words[rand() % 7];          // No need to separately declare and initialize the 'n' variable         int n = rand() % word.length();         char checkAnswer = word.at(n);          // No need for an underscore variable, because you only use it once in your code.         // One could argue that you should still keep the variable in case you wanted to change the         // symbol, but your variable name indicates that it equals to '_', so you wouldn't use it         // for that.(What I meant is if you wanted to change "A_pha" to, let's say, "A*pha")         word.at(n) = '_';          std::cout << word << ' ';         char answer;         std::cin >> answer;          if (answer == checkAnswer){             std::cout << "Correct! ";         }         else{             // Prefer ++a to a++. It doesn't matter in this case, but it's a good practice             ++faults;         }     } }  int hangman(){     // Switch statement may have been more fitting here, but I'm too lazy to rewrite     // your code, so do it yourself if you want to :P     if (faults == 0){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|" << std::endl;     std::cout << "|" << std::endl;     std::cout << "|" << std::endl;     return 1;     }     else if (faults == 1){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|" << std::endl;         std::cout<<"|" << std::endl;         return 1;     }     else if (faults == 2){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |"<<std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|" << std::endl;             ;         return 1;     }      else if (faults == 3){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                     /" << std::endl;             ;         return 1;     }     else if (faults == 4){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      X" << std::endl;         return 1;     }     else if (faults == 5){         std::cout << "|----------------------" << std::endl;             std::cout << "|                      |" << std::endl;             std::cout << "|                      O" << std::endl;             std::cout << "|                      |" << std::endl;             std::cout << "|                      X" << std::endl;             std::cout << "                       -" << std::endl;         return 1;     }     else if (faults == 6){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      X" << std::endl;         std::cout << "                      - -" << std::endl;         return 1;     }     else if (faults == 7){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      X" << std::endl;         std::cout << "                      - -" << std::endl;         std::cout << "Dead.Dead.The hangman is dead!You lose!" << std::endl;         return 0;     }     // Again, just a design nitpick, but your images of hangman with 6 and 7 faults are identical.     // Shouldn't the hangman be dead after 6 faults then? }   
 

First of all, that's not how hangman is usually implimented, but I won't question it, I'll only review your code.

1. Make sure your code actually works

You currently have an endless while loop. Your hangman() function does not do what it's supposed to, it does not update the value of i. Remove the 'i' variable entirely and change the main loop to "while(hangman()) { ... }". You should also remove the hangman() call at the end of your while loop (in the 'else' block), because it's not needed after this adjustment.

(note: that's the least you should do. I'd suggest avoiding global variables entirely (you'll still have a global variable 'faults'), but changing that would require redesigning the whole code. You should at least change 'faults' to 'g_faults' to indicate that it's a global variable)

2. Adjust the output of your program

This is sort of a minor nitpick, but your output looks ugly. A space before user input and a newline char after 'correct!' should fix it.

3. Properly indent your code

Your code as it currently is is hard to read and understand, because it does not follow the common identation rules. I'll post your code with proper indentation later.

4. Don't use the NULL macro

Especialy in this situation, there is no need for it (correct me if I'm wrong). Simply write 'time(0)'.

5. Name your variables properly

The name of your variable should make clear what the varable does. Thus, your 'word' string should be 'current_word' or at least 'cWord', the 'checkAnswer' char should be 'currentLetter' or 'missingLetter' ect.

Sorta fixed code

#include <iostream> #include <string> #include <algorithm> #include <time.h>  int faults = 0; int hangman();  // No need for 'i' variable  int main(){     // No need for NULL macro     srand(time(0));      // If you declare words[] inside the while loop, it gets created and destroyed every time the loop     // executes. There is no need for that, thus you should declare the array outside of the loop     std::string words[7]{"Alpha", "Cornwall", "Crepuscular", "Blind", "Steroid", "Plunder", "Talisman"};      while (hangman()){         std::string word = words[rand() % 7];          // No need to separately declare and initialize the 'n' variable         int n = rand() % word.length();         char checkAnswer = word.at(n);          // No need for an underscore variable, because you only use it once in your code.         // One could argue that you should still keep the variable in case you wanted to change the         // symbol, but your variable name indicates that it equals to '_', so you wouldn't use it         // for that.(What I meant is if you wanted to change "A_pha" to, let's say, "A*pha")         word.at(n) = '_';          std::cout << word << ' ';         char answer;         std::cin >> answer;          if (answer == checkAnswer){             std::cout << "Correct!\n";         }         else{             // Prefer ++a to a++. It doesn't matter in this case, but it's a good practice             ++faults;         }     } }  int hangman(){     // Switch statement may have been more fitting here, but I'm too lazy to rewrite     // your code, so do it yourself if you want to :P     if (faults == 0){     std::cout << "|----------------------" << std::endl;     std::cout << "|                      |" << std::endl;     std::cout << "|" << std::endl;     std::cout << "|" << std::endl;     std::cout << "|" << std::endl;     return 1;     }     else if (faults == 1){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|" << std::endl;         std::cout<<"|" << std::endl;         return 1;     }     else if (faults == 2){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |"<<std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|" << std::endl;             ;         return 1;     }      else if (faults == 3){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                     /" << std::endl;             ;         return 1;     }     else if (faults == 4){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      X" << std::endl;         return 1;     }     else if (faults == 5){         std::cout << "|----------------------" << std::endl;             std::cout << "|                      |" << std::endl;             std::cout << "|                      O" << std::endl;             std::cout << "|                      |" << std::endl;             std::cout << "|                      X" << std::endl;             std::cout << "                       -" << std::endl;         return 1;     }     else if (faults == 6){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      X" << std::endl;         std::cout << "                      - -" << std::endl;         return 1;     }     else if (faults == 7){         std::cout << "|----------------------" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      O" << std::endl;         std::cout << "|                      |" << std::endl;         std::cout << "|                      X" << std::endl;         std::cout << "                      - -" << std::endl;         std::cout << "Dead.Dead.The hangman is dead!You lose!" << std::endl;         return 0;     }     // Again, just a design nitpick, but your images of hangman with 6 and 7 faults are identical.     // Shouldn't the hangman be dead after 6 faults then? } 
 
 
 
 
2
 
vote

Ya has conseguido lo que creo que es un buen comentario, así que intentaré no repetirlo. Aunque veo algunas cosas más, creo que están abiertas a la mejora.

Evite las variables globales

Primero, prefiero pasar faults como un parámetro en la función hangman en lugar de usar una variable global:

  int hangman(int faults) {      // ...   

No te repitas

Segundo, no estoy entusiasmado con la cantidad de repetición que hay en el código para la función hangman . Prefiero ver los datos consolidados en un solo lugar, y la lógica refleja la del juego en sí más de cerca. Algo en este orden me parece más razonable:

  void hangman(int faults) {     static char const *body[] = {         "|                     O ",         "|                     | ",         "|                     X ",         "|                    - - ",         "Dead.Dead.The hangman is dead!You lose! "     };      std::cout << "|---------------------- |                     | ";      if (faults > 5)         faults = 5;      int i;     for (i = 0; i < faults; i++)         std::cout << body[i];     for (; i < 5; i++)         std::cout << "| "; }   

No use rand

Durante algún tiempo (desde C ++ 11) Hemos tenido mejores instalaciones de generación de números aleatorios que srand / rand8 disponible. En lugar de discutir NULL vs. faults0 , use ellos y no llame faults1 en absoluto. Desafortunadamente, el uso de estos como lo proporcionan la biblioteca es algo verboso y doloroso, por lo que encapsule una forma razonable de usarlos en una clase pequeña:

  faults2  

Con esto, definirías algo como esto:

  faults3  

... y generar un número como este:

  faults4  
 

You've already gotten what I think is some good feedback, so I'll try not to repeat it. I do see a few more things I think are open to improvement though.

Avoid global variables

First, I'd rather pass faults as a parameter to the hangman function rather than using a global variable:

int hangman(int faults) {      // ... 

Don't Repeat Yourself

Second, I'm not excited about how much repetition there is in the code for the hangman function. I'd rather see the data consolidated into one place, and the logic reflect that of the game itself more closely. Something on this order seems more reasonable to me:

void hangman(int faults) {     static char const *body[] = {         "|                     O\n",         "|                     |\n",         "|                     X\n",         "|                    - -\n",         "Dead.Dead.The hangman is dead!You lose!\n"     };      std::cout << "|----------------------\n|                     |\n";      if (faults > 5)         faults = 5;      int i;     for (i = 0; i < faults; i++)         std::cout << body[i];     for (; i < 5; i++)         std::cout << "|\n"; } 

Don't use rand

For some time now (since C++11) we've had better random number generation facilities than srand/rand available. Rather than argue about NULL vs. 0, use them and don't call time at all. Unfortunately, using these as they're provided by the library is somewhat verbose and painful, so I encapsulate one reasonable way to use them in a tiny class:

class generator {     std::mt19937 rng;     std::uniform_int_distribution<int> uni; public:     generator(int low, int high) : rng(std::random_device()()), uni(low, high) { }     int operator()() { return uni(rng); } }; 

With this, you'd define something like this:

generator gen(0, word.length()-1); 

...and generate a number like this:

n = gen(); 
 
 

Relacionados problema

2  Juego Hangman completado  ( Completed hangman game ) 
Esto funciona en su mayor parte. Soy muy nuevo en la programación, así que sé consciente. import java.util.*; public class HangManP5 { private static Scan...

4  Hangman en Java  ( Hangman in java ) 
Tengo el siguiente código en Java: HangmanFunctions Clase: import java.util.ArrayList; import java.util.Random; public class HangmanFunctions { pr...

5  Revisión de código para Hangman en C ++  ( Code review for hangman in c ) 
Tengo el siguiente programa C ++: autoConnect.py1 que se supone que replica visualmente el juego clásico de Hangman. ¿El código está totalmente optimiza...

3  Hangman en bash  ( Hangman in bash ) 
reglas 7 errores permitidos. Reglas de la Hangman. descargo de responsabilidad No tengo una figura (dibujo) del Hangman, ya que este proyecto se...

8  Juego de Hangman simple en C ++  ( Simple hangman game in c ) 
Estoy tratando de crear un juego de Hangman simple. El juego tiene un modo de edición para la primera ejecución en la que el usuario tiene que suministrar 6 p...

43  La forma correcta de colgar a un hombre  ( The right way to hang a man ) 
Problema: He visto algunas preguntas sobre Hangman. Por lo general, esto se hace de una manera muy hackeable, que generalmente no se puede generalizar más. ...

8  My Hangman Game creó usando Pyqt5 y Python 3.5  ( My hangman game created using pyqt5 and python 3 5 ) 
Este es mi juego de Hangman que creé con Pyqt5 y Python 3.5 en mi máquina Windows 7. ¿Qué piensas? ¿Hay algo en lo que pueda cambiar / mejorar en términos de ...

5  La forma correcta de colgar un hombre: parte final  ( The right way to hang a man final part ) 
El problema: Haciendo un juego de Hangman simple. Esta es una continuación de la siguiente pregunta: la forma correcta de colgar un hombre . Allí acababa d...

12  Juego Simple de Hangman  ( Simple game of hangman ) 
En mi búsqueda para convertirse en un programador maestro, he creado un juego simple de Hangman, por lo que pensé que lo subiría aquí y vería cómo podría ser ...

3  Juego de Hangman escrito en Python 3.5  ( Hangman game written in python 3 5 ) 
Esto recopila las conjeturas del usuario para la palabra. El usuario tiene 8 conjeturas, una conjetura correcta y una suposición repetida no afecta al conteo ...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos