Probleme avec mon code aidez moi svp

Fermé
sou2904 Messages postés 1 Date d'inscription lundi 7 décembre 2020 Statut Membre Dernière intervention 7 décembre 2020 - Modifié le 7 déc. 2020 à 23:18
mamiemando Messages postés 33320 Date d'inscription jeudi 12 mai 2005 Statut Modérateur Dernière intervention 17 octobre 2024 - 11 déc. 2020 à 11:32
bonsoir
s'il vous plait aidez moi à activer le help pour le jeu motus et de corriger la chaine (malplace) des lettres mal placées après qu'on devine leurs positions.
merci.
voila mon code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int choix = 0;
int second;
int coups=7;
char motGame[][1000] = {"programmation","interface","structure","algorithme","logiciel","matrice","element","ascii","code","boucle","bouton","analyse","test","multimedia","communication","affaires","activation","binaire","bilan","developpement","entreprise","fournisseur","client","consultant","expert","frais","consommation","marketing","commercialisation","vente","approvisionnement","acquisition","emploi","rigide","case","datascience","bigdata","probabilite","statistique","phenomene","economie","ergonomie","adaptation","systeme","architecture","linux","fichier","repertoire","salaire","licence","automatique","ciblage","monopole"};
int randomMot;
char motsecret[] = "" ;
int score = 4;
int verify1 = 1 ;
int help = 1;
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char pseudos[100][100];
int scores[100];
int joueur ;
time_t start_t, end_t;
char malplace[1000] = "";

void getUser(){
 printf("Entrez votre nom SVP : ");
    fflush(stdin);
    fgets(pseudos[joueur],1000,stdin);
    pseudos[joueur][strlen(pseudos[joueur]) - 1] = '\0';
    scores[joueur] = 0 ;
    joueur= joueur + 1;
}

void printMenu(){
    printf("|~*~|******************-------~------***********************|~*~|\n");
    printf("|~*~|------------------*****************--------------------|~*~|\n");
    printf("|~*~|*******************BIENVENUE AU JEU********************|~*~|\n");
    printf("|~*~|-------------------****************--------------------|~*~|\n");
    printf("|~*~|*******************------~-------**********************|~*~|\n");
    printf("\n");
    printf("\n");
    printf("|~*~|-------------------------------------------------------|~*~|\n");
    printf("|~*~|-------------------------------------------------------|~*~|\n");
    printf("|~*~|               VEUILLEZ CHOISIR UN JEU                 |~*~|\n");
    printf("|~*~|-------------------------------------------------------|~*~|\n");
    printf("|~*~|*******************************************************|~*~|\n");
    printf("|~*~|~~~~~~~~~~~~~~~~~~~ 1- LE PENDU ~~~~~~~~~~~~~~~~~~~~~~~|~*~|\n");
    printf("|~*~|~~~~~~~~~~~~~~~~~~~ 2- MOTUS ~~~~~~~~~~~~~~~~~~~~~~~~~~|~*~|\n");
    printf("|~*~|*******************************************************|~*~|\n");
    printf("|~*~|-------------------------------------------------------|~*~|\n");
    printf("|~*~|                    3- QUITTER                         |~*~|\n");
    printf("|~*~|-------------------------------------------------------|~*~|\n");
    printf("|~*~|-------------------------------------------------------|~*~|\n");
}

void menuFin(){
 printf("|~*~|---------------------------------------------------------|~*~|\n");
    printf("|~*~|           ~*~ 1- REJOUER LE PENDU ~*~                   |~*~|\n");
    printf("|~*~|             ~*~ 2- REJOUER MOTUS ~*~                    |~*~|\n");
    printf("|~*~|            ~*~ 3- VERIFIER SCORE ~*~                    |~*~|\n");
    printf("|~*~|               ~*~ 4- CLASSEMENT ~*~                     |~*~|\n");
    printf("|~*~|        ~*~ 5- RETOUR AU MENU PRINCIPAL ~*~              |~*~|\n");
    printf("|~*~|          ~*~ 6- QUITTER L'APPLICATION ~*~               |~*~|\n");
 printf("|~*~|---------------------------------------------------------|~*~|\n");
 printf("|~*~|---------------------------------------------------------|~*~|\n");
    printf("Entrez votre choix SVP : ");
    scanf("%d",&choix);
    while((choix!=1)&&(choix!=2)&&(choix!=3)&&(choix!=4)&&(choix!=5)&&(choix!=6))
    {
        printf("Commande introuvabe veuillez entrez le numero de un des commandes \n");
        scanf("%d",&choix);
    }
    if (choix == 1 ){
     LePendu();
    }
      else if(choix == 2){
     LeMotus();
 }
    else if(choix == 3){
     printScore();
 }
 else if(choix == 4){
  printClassement();
 }
 else if(choix == 5){
  main();
 }
 else if (choix == 6){
  exit(0);
 }
}

void printScore(){
 printf("|~*~|-------------------------------------------------------|~*~|\n");
 printf("|~*~|************** votre score est : %d ******************|~*~|\n",scores[joueur - 1]);
 printf("|~*~|-------------------------------------------------------|~*~|\n");
 menuFin();
}

void printClassement(){
 int i;
 for (i = 0; i < joueur; i++)
 {
  int j;
  for (j = 0; j < joueur; j++)
  {
   if (scores[j] < scores[i])
   {
    char tri1[1000];
    strcpy(tri1, pseudos[i]);
    pseudos[i][0] = '\0';
    strcpy(pseudos[i], pseudos[j]);
    pseudos[j][0] = '\0';
    strcpy(pseudos[j], tri1);
    int tri2 = scores[i];
    scores[i] = scores[j];
    scores[j] = tri2;
   }
  }
 }
 printf("************************* CLASSEMENT *****************************\n");
 printf("----------------------- Pseudo  Score --------------------------\n");
 int k;
 for(k = 0; k < joueur; k++ ){
  printf(" ~~~~~~~~~~~~~~~~~~~%s            %d ~~~~~~~~~~~~~~~~~~~\n",pseudos[k],scores[k]);
    }
 menuFin();
}

int main(){
 printf("\n");
 getUser();
    printMenu();
    printf("Entrez  votre choix SVP : ");
    scanf("%d",&choix);
    while((choix!=1)&&(choix!=2)&&(choix!=3))
    {
        printf("Commande introuvabe veuillez entrez le numero de un des commandes \n");
        scanf("%d",&choix);
    }
        switch (choix){
   case 1:
    LePendu();
    break;
   case 2:
    LeMotus();
    break;
   case 3:
    exit(0);
  }

    return 0 ;
}
void pendu()
{
    printf("  _____\n");
    printf(" |    |\n");
    printf(" |    |\n");
    printf(" |    °\n");
    printf(" |\n");
    printf(" |\n");
    printf(" -\n");

}

void LePendu(){
 srand(time(NULL));
 randomMot = rand() % 53;
 int i;
    motsecret[0] = '\0';
    for(i = 1; i < strlen(motGame[randomMot]) + 1; i++ ){
        strncat(motsecret, "*", 1);
    }
    alphabet[0] = '\0';
    strcpy(alphabet, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");

 score = 4;
 verify1 = 1 ;
 help = 1;
 coups = 7;
 time(&start_t);
 int error = 0 ;
    while(coups > 0 && verify1 != 0){
        printf("Il vous reste ");
        printf("%d",coups);
        printf(" coups a jouer et ");
        second = 70 - difftime(time(&end_t), start_t);
        printf("%d",second);
        printf(" secondes \n");
        printf("Quel est le mot secret ? ");
        printf(motsecret);
        printf("\n");
        int k;
        for(k=0;k<strlen(alphabet);k++){
            printf("%c     ",alphabet[k]);
        }
        printf("\n");
        printf("Tapez '?' pour help \n \n");
        printf("Proposez une lettre pour sauver votre vie : ");
        char mot;
        if( 70 - difftime(time(&end_t), start_t) <=0 ){
         printf("\n DOMMAGE , le temps s'est ecoule\n Le mot secret est : %s",motGame[randomMot]);
         pendu();
         break;
  }
        fflush(stdin);
        mot = getchar();
        int verfy = 0;
        if (mot == '?' && help == 1){
         int randomHelp;
         do{
          srand(time(NULL));
          randomHelp = rand() % strlen(motGame[randomMot]);
          mot = motGame[randomMot][randomHelp];
   }
   while(motsecret[randomHelp] != '*');
         score = score - 1;
         help--;
  }
   if (mot == '?' && help == 0)
         {
             printf(" \n Vous avez deja utilise votre chance unique de help\n");
         }
  int i;
        for(i=0;i<strlen(motGame[randomMot]);i++){
            if(toupper(mot) == toupper(motGame[randomMot][i])){
                verfy = 1;
                motsecret[i] = motGame[randomMot][i];
                int alpha = strchr(alphabet,toupper(mot)) - alphabet;
                if ( alpha >= 0 ){
                 alphabet[alpha] = '-';
    }
            }
        }
        if(verfy == 0){
         error = error + 1 ;
            int errScore = error / 2;
            score = 4 - errScore;
            coups--;
        }
        verify1 = strcmp(motsecret,motGame[randomMot]);
        if(verify1 == 0){
            printf(" BRAVO VIE SAUVEE ! Le mot secret est devoile : %s \n", motsecret);
            printf("Votre score est : %d", score);
        }
        printf("\n");
    }
    if(verify1 != 0){
     score = 0;
        printf("Vous avez perdu!\n PENDU ! \n");
        pendu();
    }
    scores[joueur - 1] = scores[joueur - 1] + score;
    printf("\n");
    menuFin();
}
void LeMotus(){
    malplace[0]='\0';
    srand(time(NULL));
    randomMot = 1;
    int i;
    motsecret[0] = '\0';
    motsecret[0] = toupper(motGame[randomMot][0]);
    for(i=1;i<strlen(motGame[randomMot]);i++)
    {
        strncat(motsecret,"*",1);
    }
    score=4;
    verify1=1;
    help=1;
    coups=7;
    time(&start_t);
    int error=0;
    while((coups>0) && ( verify1!=0))
    {
        printf("Il vous reste ");
        printf("%d",coups);
        printf(" coups a jouer et ");
        second = 70 - difftime(time(&end_t), start_t);
        printf("%d",second);
        printf(" secondes \n");
        printf("Quel est le mot secret ? ");
        printf(motsecret);
        if (strlen(malplace) > 0){
            printf(" [%s]",malplace);
        }        // **
        printf("\n");
         printf("Tapez '?' pour help \n \n");
        printf("Proposez un mot compose de %d lettres pour sauver votre vie : ",strlen(motGame[randomMot]));
        char mot[1000];
        if( 70 - difftime(time(&end_t), start_t) <=0 ){
         printf("\n Desole, le temps s'est ecoule\n");
         break;
  }
        fflush(stdin);
        fgets(mot,1000,stdin);
  int verfy=0;
  if ((mot[0] == '?') && (help == 1)){
         int randomHelp;
         do{
          srand(time(NULL));
          randomHelp = rand() % strlen(motGame[randomMot]);
          mot[randomHelp] = motGame[randomMot][randomHelp];
   }
   while(motsecret[randomHelp] != '*');
         score = score - 1;
         help--;
  }
        int i;
        for(i=0;i<=strlen(motGame[randomMot]);i++)
        {
            int j;
            for(j=0;j<strlen(mot);j++)
            {
                if (toupper(mot[j])==toupper(motGame[randomMot][i]))
                {
                    verify1=1;

                    if( i == j ){
                        motsecret[i]=motGame[randomMot][i];
                    }
                    else {
                        int verifyChar = strchr(malplace,motGame[randomMot][i]) - motGame[randomMot][i];
                        if (verifyChar < 0){
                            malplace[strlen(malplace)] = motGame[randomMot][i];
                        }
                        if(malplace[j]==motsecret[j])
                        {
                            malplace[j]='-';
                        }
                    }

                }
            }
        }
        if(verfy==0)
        {
            error++;
            int errscore=error/2;
            score=4-errscore;
            coups--;
        }
        verify1=strcmp(motsecret,motGame[randomMot]);
        if (verify1==0)
        {
            printf(" Le mot secret est devoile: %s \n ",motsecret);
            printf("Votre score est = %d \n",score);
        }
    }
    if (verify1!=0)
    {
      score = 0;
        printf("Dommage ! Vous avez perdu \n Le mot secret est :%s",motGame[randomMot]);
    }
      scores[joueur - 1] = scores[joueur - 1] + score;
    printf("\n");
    menuFin();

}
A voir également:

1 réponse

mamiemando Messages postés 33320 Date d'inscription jeudi 12 mai 2005 Statut Modérateur Dernière intervention 17 octobre 2024 7 798
Modifié le 11 déc. 2020 à 11:40
Bonjour,

Plusieurs remarques :
  • J'imagine que tu débutes en C, mais sache que les variables globales sont une mauvaise habitude. Cela complexifie le débogage (notamment pour suivre qui peut modifier telle ou telle variable). Normalement il vaut mieux passer tes variables en paramètres des fonctions appelées. Typiquement tes chaînes de caractères devraient être passées de fonction en fonction par pointeur (
    char *
    ). Mais pour le moment tu peux ignorer cette remarque.
  • Comme tes fonctions ne sont pas toutes déclarées avant d'être utilisées (si on lit le fichier de haut en bas), déclare tes fonctions en début de fichiers, cela évitera les warnings :


int main();
void LeMotus();
void printScore();
void printClassement();
void LePendu();
  • Inclue le header
    <ctype.h>
    pour éviter le warning liées à
    toupper
    :


#include <ctype.h>
  • Quelques incohérences restantes dans ton code :


warning: initialization of ‘int’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
325 | int verifyChar = strchr(malplace,motGame[randomMot][i]) - motGame[randomMot][i];


Effectivement strchr retourne un
char *
et non un
int
donc cette soustraction n'a pas de sens (du moins, pas celle que tu crois).
  • Ensuite ici il y a deux erreurs mémoires (potentielles segmentation fault)


toto.c:175:9: warning: ‘strncat’ specified bound 1 equals destination size [-Wstringop-overflow=]
175 | strncat(motsecret, "*", 1);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~
toto.c: In function ‘LeMotus’:
toto.c:269:9: warning: ‘strncat’ specified bound 1 equals destination size [-Wstringop-overflow=]
269 | strncat(motsecret,"*",1);
|


En effet, le 3e paramètre de n ne signifie que n caractères doivent être recopiés, mais le nombre maximal de caractères qui peuvent encore être recopiés dans le buffer destination (voir
man strncat
).

Exemple :

#include <string.h>
#include <stdio.h>

int main(){
    char motsecret[100];
    unsigned i;
    for (i = 0; i < 5; i++) {
        strncat(motsecret, "*", 100 - i);
    }          
    printf("%s", motsecret);
    return 0;
}


Mais le plus simple, c'est juste de remplacer tes
strncat(motsecret, "*", 1)
par
strcat(motsecret, "*")
. En effet, comme
"*"
est une chaine statique, tu as la certitude qu'elle s'achève par un
'\0'
, et donc utiliser
strncat
n'apporte pas de garantie supplémentaire dans ton cas particulier.

Ensuite pour poser ta question, voilà ce que je te propose :
  • Fais un code minimal, qui met en évidence le problème, et dis-nous quel est ce problème et ce qui te bloque. Typiquement si ton code a pour but de faire un motus, il ne devrait pas y avoir de pendu...
  • Précise ta question car là on ne sait pas ce qui te bloque / ce que tu veux faire.


Bonne chance
0