code implementation

Asked

Viewed 199 times

0

I and a colleague are beginners in programming and we are building a game in which we need to use chained list. He was responsible for creating a game menu using chained list and I for creating the game. Only now we need to put the codes together and it turns out we’re not making it.

I need a huge help from you guys to know how I make the game behave this way. In the Menu created the user will insert the words in the list using option 1, after the words are inserted the user enters option 4 and the game makes a Random of the inserted words and puts in the game to be discovered.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <time.h>
struct no
{
char info[15];
struct no*prox;
};
typedef struct no Lista;
void jogo() { 
char palavra[25],letra[25],lacuna[25]; 
int vida=6,x=0,i,u,total=0,cont=0; 


printf("                    ******************************");
printf("\n                            JOGO DA FORCA \n");
printf("                    ******************************\n");

printf("\n                             BOM JOGO\n\n");

printf("\nDIGITE A PALAVRA E TECLE ENTER PARA CONTINUAR");
printf("\n\nPALAVRA: ");

gets(palavra); 
fflush(stdin);

system("cls");

for(i=0;i<strlen(palavra);i++) 
{ 
lacuna[i]='X'; 
total++;
cont++;
} 

while(vida>0) 
{ 

printf("\nA PALAVRA COMTEM %i LETRAS\n",total);
printf("\nLETRAS RESTANTES: %i\n",cont);


printf("\n%s\n",lacuna); 
printf("\nENTRE COM UMA LETRA: "); 
gets(letra); 
system("cls");

for(i=0;i<strlen(palavra);i++) 
{ 
for(u=0;u<strlen(palavra);u++){
if(letra[u]==palavra[i]) 
{ 
lacuna[i]=palavra[i]; 
x++; 
cont--;
}
} 
} 

if(cont==0){
printf("PARABENS! VOCE VENCEU!");   
printf("\nACERTOU A PALAVRA %s", palavra);
}

if(x==0) 
{ 
vida--; 
printf("\nVOCE PERDEU UMA VIDA!\nVOCE TEM %d VIDA(S) 
RESTANTES\n\n",vida); 

} 
 x = 0;
}

printf("\n\nVC FOI ENFORCADO, Fim de jogo!\n\n\nPALAVRA SECRETA: 
%s",palavra);

printf("\n\n***********************\n\n");
printf("* JOGO DA FORCA *\n\n");
printf(" ___ \n");
printf(" | | \n");
printf(" | O  \n");
printf(" |/|\ \n");
printf(" | |  \n");
printf(" |/ \  \n");
printf(" |______ \n");
printf("\n**********************\n");

getchar(); 
getchar(); 
}
void cria (Lista **L)
{
*L=NULL;
}
void Ins_Inicio (Lista **L, char v[15])
{
Lista *p = (Lista *) calloc (1, sizeof(Lista));
 strcpy(p->info, v); 
p->prox=*L;
*L = p;
}
void imprime (Lista *L)
{
Lista*p;
p=L;
while (p != NULL)
{
printf("%s-->", p->info);
p=p->prox;
}
printf("NULL\n");
}
void jogar (Lista *L)
{
int num, total_nos=0;
Lista *p;
 p=L;
while (p!=NULL)
{
total_nos++;
p=p->prox;
}

int rand();
num = rand()+ (total_nos)+1;
while (p != NULL)
{ 
}}
main()
{
char palavra[25],letra[25],lacuna[25]; 
int vida=6,x,i; 

 Lista *L;
 int op, ret, fim;
 char val[15];
 cria(&L); 
 do 
 {
 int clrscr();
puts("1 - Insere palavras no INICIO da lista");
puts("2 - Remove palavras da lista");
puts("3 - IMPRIMIR a lista");
puts("4 - Jogar");
puts("5 - Sair");
puts("\nDigite a opcao desejada");
scanf("%d", &op);

switch(op)
{
case 1: puts("Digite o valor a ser inserido:");
    fflush(stdin);
    gets(val);
    Ins_Inicio(&L,val);
    break;

case 2: puts("Digite o valor a ser removido");
    fflush(stdin);  
    gets(val);

    break;
case 3: imprime(L);
    getch();
    break;
case 4: jogar(L);
    jogo();
    break;
}
}
while(op!=5);
 }
  • Here is an offtoic recognition: if you want to learn "C" - stand firm on the path you have chosen. If you want to learn "programming" and do this by creating games-like programs that are playable on the way - I recommend using another language - more "high-level" (this is not pejorative, it’s just a way of classifying languages) - like Python, Javascript, or Ruby.

  • I disagree @jsbueno. Making a game for a language you are learning is a great way to test your knowledge.

  • Hi Francisco - so you agree with me - see what I wrote: "if you want to learn C, keep on going". My observation is that if they want to learn to program codes of the type of this game, but can be with a language that facilitates this.

  • @jsbueno It’s easier to become a PP or PC than to study C!!!

2 answers

0


In your case, you put your whole code in main, which is functional, but it’s wrong. To join the 2 codes, you can create a method in your friend’s code with your entire code and call from the switch.

switch(op)
{
case 1: puts("Digite o valor a ser inserido:");
    fflush(stdin);
    gets(val);
    Ins_Inicio(&L,val);
    break;
case 2: puts("Digite o valor a ser removido");
    fflush(stdin);  
    gets(val);
    break;
case 3: imprime(L);
    getch();
    break;
case 4: jogar(L);
    jogo(); //Aqui seria onde você chamaria o seu método.
    break;
}

To pick up a random word that is in the struct, you can use the rand() in this way:

Lista L; 
pergunta = rand() % sizeof(L.info);

If you have difficulties to do this, comment below that I can help you.

EDIT: Code ready below. (It’s disorganized because I took yours as a base.)

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <time.h>
struct no
{
char info[15];
struct no*prox;
};
typedef struct no Lista;
void jogo() { 
char palavra[25],letra[25],lacuna[25]; 
int vida=6,x=0,i,u,total=0,cont=0; 


printf("                    ******************************");
printf("\n                            JOGO DA FORCA \n");
printf("                    ******************************\n");

printf("\n                             BOM JOGO\n\n");

printf("\nDIGITE A PALAVRA E TECLE ENTER PARA CONTINUAR");
printf("\n\nPALAVRA: ");

gets(palavra); 
fflush(stdin);

system("cls");

for(i=0;i<strlen(palavra);i++) 
{ 
lacuna[i]='X'; 
total++;
cont++;
 } 

while(vida>0) 
{ 

printf("\nA PALAVRA COMTEM %i LETRAS\n",total);
printf("\nLETRAS RESTANTES: %i\n",cont);


printf("\n%s\n",lacuna); 
printf("\nENTRE COM UMA LETRA: "); 
gets(letra); 
system("cls");

for(i=0;i<strlen(palavra);i++) 
{ 
for(u=0;u<strlen(palavra);u++){
if(letra[u]==palavra[i]) 
{ 
lacuna[i]=palavra[i]; 
x++; 
cont--;
}
} 
} 

if(cont==0){
printf("PARABENS! VOCE VENCEU!");   
printf("\nACERTOU A PALAVRA %s", palavra);
}

if(x==0) 
{ 
vida--; 
printf("\nVOCE PERDEU UMA VIDA!\nVOCE TEM %d VIDA(S) 
RESTANTES\n\n",vida); 

} 
 x = 0;
}

  printf("\n\nVC FOI ENFORCADO, Fim de jogo!\n\n\nPALAVRA SECRETA: 
%s",palavra);

  printf("\n\n***********************\n\n");
  printf("* JOGO DA FORCA *\n\n");
  printf(" ___ \n");
  printf(" | | \n");
  printf(" | O  \n");
  printf(" |/|\ \n");
  printf(" | |  \n");
  printf(" |/ \  \n");
  printf(" |______ \n");
  printf("\n**********************\n");

  getchar(); 
  getchar(); 
  }
void cria (Lista **L)
{
*L=NULL;
}
void Ins_Inicio (Lista **L, char v[15])
{
Lista *p = (Lista *) calloc (1, sizeof(Lista));
strcpy(p->info, v); 
p->prox=*L;
*L = p;
}
void imprime (Lista *L)
{
Lista*p;
p=L;
while (p != NULL)
{
    printf("%s-->", p->info);
    p=p->prox;
}
printf("NULL\n");
}
void jogar (Lista *L)
{
int num, total_nos=0;
Lista *p;
p=L;
while (p!=NULL)
{
  total_nos++;
  p=p->prox;
}

  int rand();
  num = rand()+ (total_nos)+1;
 while (p != NULL)
 { 
 }}
main()
{
char palavra[25],letra[25],lacuna[25]; 
int vida=6,x,i; 

 Lista *L;
 int op, ret, fim;
 char val[15];
 cria(&L); 
 do
{
int clrscr();
    puts("1 - Insere palavras no INICIO da lista");
    puts("2 - Remove palavras da lista");
    puts("3 - IMPRIMIR a lista");
    puts("4 - Jogar");
    puts("5 - Sair");
    puts("\nDigite a opcao desejada");
    scanf("%d", &op);

    switch(op)
    {
    case 1: puts("Digite o valor a ser inserido:");
        fflush(stdin);
        gets(val);
        Ins_Inicio(&L,val);
        break;

    case 2: puts("Digite o valor a ser removido");
        fflush(stdin);  
        gets(val);

        break;
    case 3: imprime(L);
        getch();
        break;
    case 4: jogar(L);
        jogo();
        break;
    }
}
while(op!=5);
}
  • I did not quite understand your explanation. I would like a better help.

  • Only copy and paste.

  • Good morning @Francisco, I just tested your answer and realized that the game is not happening as expected. See if you can help me. I would like the game to behave as follows. In the Menu created the user will insert the words in the list using option 1, after the words are inserted the user enters option 4 and the game makes a Random of the inserted words and puts in the game to be discovered. I tested your code and unfortunately it did not work as expected. I appreciate if you can continue helping.

  • I don’t even know much about C, I’m helping with the knowledge I have in C#. Mark the answer as correct and specify further what is currently happening in the program, when I get home I can help you.

  • I edited my answer with a way to catch the word randomly.

0

The most important thing when creating a program in parts, each part by a different person, as you are doing, is to establish between you what will be the interface between the code of the two: that is, how the code of the one will communicate with the code of the other.

In this case, your colleague made a menu that will start the game and deal with the word list (registration, removal, and printing) while you were responsible for the game itself. So the only thing you need it for is the word to use, and it doesn’t need anything from you. So I suggest it calls a function jogar() passing the chosen word as parameter and receiving void, that is, nothing:

void
jogar(char palavra[TAM_MAX_PALAVRA]);

You implement the function jogar() and he calls her at the right time there at option 4.

Note that I put in the vector size that the jogar() receives the identifier TAM_MAX_PALAVRA, instead of 15 or 25. This is a Preprocessor constant (which we will define below) that allows you to ensure that all parts that need to deal with words will handle the same vector size, vector size TAM_MAX_PALAVRA. His definition is:

#define TAM_MAX_PALAVRA 25

To sacramentate your interface, we take the two definitions above and put in a file called jogo.h, your file header for the game:

#ifndef DEFINI_JOGO_H
#define DEFINI_JOGO_H

#define TAM_MAX_PALAVRA 25
extern void
jogar(char palavra[TAM_MAX_PALAVRA]);

#endif

So let’s take your colleague’s code and put it in the file menu.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "jogo.h"

/* Tipos de dados */

struct no {
    char info[TAM_MAX_PALAVRA];
    struct no * prox;
};

typedef struct no Lista;

/* Funções de manipulação de listas encadeadas */

void
Ins_Inicio(Lista **L, char v[TAM_MAX_PALAVRA]) {
    Lista *p = calloc(1, sizeof(Lista));
    strcpy(p->info, v); 
    p->prox = *L;
    *L = p;
}

void
imprime (Lista *L) {
    Lista *p;
    p = L;
    while (p != NULL) {
        printf("%s-->", p->info);
        p = p->prox;
    }
}

void
apagar(Lista ** L, char chave[TAM_MAX_PALAVRA]) {
    printf("TODO: me implemente\n");
}

char *
escolher_palavra_ao_acaso(Lista * L) {
   /* a implementação será feita abaixo */
}

/* funções para tratar do menu */

int
menu() {
    int resultado;
    clrscr();
    puts(
        " *****************\n"
        " * JOGO DA FORCA *\n"
        " *****************\n\n"
        "1 - Insere palavras no INICIO da lista"\n"
        "2 - Remove palavras da lista\n"
        "3 - IMPRIMIR a lista\n"
        "4 - Jogar\n"
        "5 - Sair\n\n"
        "Digite a opcao desejada"
    );
    while (scanf("%d", &resultado) < 1) {
        puts("Não entendi");
    }
    return resultado;
}

int
main(void) {
    int opcao = 0;
    Lista * L;
    char val[TAM_MAX_PALAVRA];

    srand(time(NULL));
    do {
        opcao = menu();
        switch (opcao) {
            case 1:
                puts("Digite o valor a ser inserido:");
                fflush(stdin);
                fgets(val, TAM_MAX_PALAVRA, stdin);
                Ins_Inicio(&L,val);
                break;
            case 2:
                puts("Digite o valor a ser removido");
                fflush(stdin);  
                fgets(val, TAM_MAX_PALAVRA, stdin);
                apagar(&L,val);
                break;
            case 3:
                imprime(L);
                break;
            case 4:
                jogar(escolher_palavra_ao_acaso(L));
                break;
            case 5:
                puts("Saindo...");
                break;
            default:
                puts("Opção inválida");
                break;
        }
    } while (opcao != 5);

    return 0;
}

As you can see, the file jogo.h was included using quotation marks, and not smaller-than and larger-than, for the compiler to look for the file in the same directory as the files. c and not in the directory where stdio.h and colleagues. Also we broke the larger functions into several small ones with descriptive names: for example, have a menu() which shows the menu, receives the option and delivery as return value so that the main() do not have to worry about it; and the jogar() receives a word that escolher_palavra_ao_acaso() will receive.

Let’s implement then escolher_palavra_ao_acaso():

char *
escolher_palavra_ao_acaso(Lista * L) {
    int num_palavras = 0, i = 0;
    Lista * p;

    /* Contar o número de palavras atual */
    for (p = L; p != NULL; num_palavras ++, p = p->prox);
    /* n vai receber um número aleatório entre 0 e num_palavras - 1 */
    n = rand() % num_palavras;
    /* começando do princípio da lista, andar n passos */
    for (p = L; n > 0; n --, p = p->prox);

    return n->info;
}

As for the game, you create another file teste.c in order to test the development of its:

#include <stdio.h>
#include <stdlib.h>
#include "jogo.h"

int
main(void) {
    jogar("itaquaquecetuba");
}

And finally the implementation of the routine jogar() in jogo.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include "jogo.h"

/* uma struct para guardar todas as informações sobre o estado do jogo */
struct estado {
    char * palavra;
    int tam_palavra;
    char lacunas[TAM_MAX_PALAVRA];
    int vidas;
    int faltam;
};

int
testar_letra(struct estado * e, char c) {
    int i;
    int resultado = 0;

    /* transforma letras maiúsculas em minúsculas */
    if (c >='A' && c <='Z') c -= 32;
    /* verifica se é uma letra válida*/
    if (c < 'a' || c > 'z') return resultado;
    /* procura por c em palavra; onde houver, preenche a lacuna correspondente */
    for (i = 0; i < e->tam_palavra; i ++) {
        if (e->palavra[i] == c) {
            resultado = 1;
            faltam --;
            e->lacunas[i] = e->palavra[i];
        }
    }

    return resultado;
}

void
jogar(char * palavra) {
    int i;
    struct estado e;
    char c;

    /* inicializa o estado do jogo */
    e.palavra = palavra;
    e.vidas = 6;
    e.faltam = e.tam_palavra = strlen(palavra);
    for (i = 0; i < e.tam_palavra; i ++)
        e.lacunas[i] = 'X';
    e.lacunas[i] = '\0';

    clrscr();
    while (e.vidas > 0) {
        printf("\nA PALAVRA COMTEM %d LETRAS\n"
               "\nLETRAS RESTANTES: %d\n",e.tam_palavra, e.faltam);
        printf("\n%s\n", e.lacunas);
        printf("\nENTRE COM UMA LETRA: ");
        /* limpa o buffer */
        fflush(stdin);
        c = getchar();
        if (! testa_letra(&e, c)) {
            e.vidas--;
            printf("\nVOCE PERDEU UMA VIDA!\n"
                   "VOCE TEM %d VIDA(S) RESTANTES\n\n",vida);
            if (e.vidas == 0) {
                printf("\n\n"
                       "VC FOI ENFORCADO, Fim de jogo!"
                       "\n\n\n"
                       "PALAVRA SECRETA: %s",palavra);

                printf("\n\n***********************\n\n"
                       "* JOGO DA FORCA *\n\n"
                       " ___ \n"
                       " | | \n"
                       " | O  \n"
                       " |/|\ \n"
                       " | |  \n"
                       " |/ \  \n"
                       " |______ \n"
                       "\n**********************\n");
                return;
            }
        } else if (e.faltam == 0) {
            printf("PARABENS! VOCE VENCEU!"
                   "\nACERTOU A PALAVRA %s", palavra);
            return;
        }
    }
}

Then, when compiling the game, you compile the two modules jogo.c and menu.c together. Since you must be using an IDE, there’s no need to comment on command line options, but it’s super simple. Compile jogo.c and menu.c for the full game, or jogo.c and teste.c to test only your part.

  • Friend, we are beginners and got a bit confused. Is there any way to get the code ready for each file? we are starting the course and we started studying together. Thanks for the help. @Wtrmute

  • The codes are separated by file. The only job you would have would be to insert the implementation of the function escolher_palavra_ao_acaso() over the stub that is where it should go. I know the answer is long; bigger than it probably should be. But don’t be too lazy to read, because C is a language that doesn’t forgive the lack of attention...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.