Hangman game problem

This is a discussion on Hangman game problem within the C Programming forums, part of the General Programming Boards category; Hello everybody, For the past days, I've been googling like a maniac looking for information so I would be able ...

  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    3

    Hangman game problem

    Hello everybody,

    For the past days, I've been googling like a maniac looking for information so I would be able to solve this problem, but I haven't been able to.

    Everybody knows the Hangman game, you get a word, you guess, and if you miss too much, you get hanged.

    I've got most of the "easy" part of the game done, but there is one thing that is bugging me a lot.

    I thought of doing the game in 3 different ways, two of them which I don't know how to do them even tho I've researched and looked quite a bit about working with files but the information is not extensive enough.

    1st way: Let the user put the word himself, maybe then a friend come thru and try to guess it. Way easier, but not the way I want it.

    2nd way: Have a .txt file with 1 word per line, then get a random number (which I know how to get)
    having this declared already:
    Code:
    FILE *fp;
    	int fclose(FILE *fp);
    then open the file (which I guess is this way)
    Code:
    	if ((fp = fopen("wordlist.txt", "r")) == NULL)
        {
           printf("The file could not be opened.\n");
           exit(1);        
        }
    BUT what I don't know how to do is, to use that random number to read one of the lines of the file, and pass that onto a variable that I can use so the user can try to guess the word.

    I truly hope you can help me.

    Kindest Regards,
    Piradie

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,888
    You could use fgets() to read and ignore the first n-1 lines, and then finally read the nth line as the random word.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    A perhaps easier way to look at it, unless you're word list is really really big, is to suck in all the words at once into memory when your program starts; then when you pick your random number, you can just say wordlist[random_number] and be done with it. If you're only going to play the game once, then it's a bad idea, but if you will play many times in one session than you can save a little bit of work.

  4. #4
    Registered User
    Join Date
    Dec 2006
    Location
    Scranton, Pa
    Posts
    252
    My own version works with a data file (contains all current entries (you can add, review, delete entries via control panel)) and they're retrieved by random number. The program is actually c+ , gui-based, but if you're interested in tearing thru the code if you think'd it help you, p.m. me; I'll see if I can't dig it up. I recently moved, so I have no idea where anything is. ..

    You can get the program here. (Seven Balloons).

  5. #5
    Why am I a programmer? shoutatchickens's Avatar
    Join Date
    Mar 2008
    Posts
    45
    OR!

    You could host a SQL database on your PC with a dictionary full of words along with a unique number identifier. Query the database with the random number and use the word you get back.

    Then pass the game out to all your friends and charge them 5 dollars a week to play it

  6. #6
    Registered User
    Join Date
    Dec 2008
    Posts
    15
    um..I'm still learning c, but here was my attempt at it. It isn't a complete program but, It should solve the randomizing issue. You should modify the code as you see fit.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main(void)
    {
    	
    	int wordCount=0;
    	char word[20]; /*max length of each word*/
    	int tempCount,randomNumber;
    	
    	FILE *listPtr;
    
    	/*Inputs words into a file*/
    	if ((listPtr = fopen("list.txt","w"))== NULL){
    		printf("File could not be opened\n");
    	}else 
    	    {
    	      printf("Please enter word\n");
    	      printf("Enter EOF to end input\n");
    	      scanf("%s",word);
    
    		  while (!feof(stdin)){
    		      fprintf(listPtr,"%d %s\n",wordCount++,word);
    			  printf("Please enter next word:\n");
    			  scanf("%s",word);
    		     }
    			
    		 fclose(listPtr);
    	}
    	/* close file*/
    	
    	srand(time(NULL));
    	randomNumber= rand()%wordCount; /*selects a random number from the list*/
    	
           /*read from file*/
    	if ((listPtr = fopen("list.txt","r"))== NULL){
    		printf("File could not be opened\n");
    	}else 
    	    {
    		  while (!feof(stdin)){
    		      fscanf(listPtr,"%d %s\n",&tempCount,word);
    			  
    			  if (tempCount== randomNumber)
    				  break; 
    		     }
    			
    		 fclose(listPtr);
    	}
    	
    	/*here is the random word from the list*/
    	printf("%s\n",word);
    	
    	return 0;
    }

  7. #7
    Registered User
    Join Date
    Dec 2008
    Posts
    3
    Hello,

    Thanks for all the answers, somehow I didn't receive any more notifications even though I did request it.

    Anyways . . . I've been working on the code for a little longer, and I've got this so far.

    Right now, it is opening the file correctly, generating a random number correctly (Even though I sometimes get a -1 as a random number which screws everything up, hopefully someone can suggest me something to do), but apart from that, I only have one problem left.

    As of now, as soon as it goes through the line of the random number, it grabs the word and puts it into an array (secreta[10]). My idea now is the following, as the user enters the letter (variable "guess") I want to compare it to the array so I can keep working, I just don't know how to do that.

    Any help is appreciated, thank you!

    Code:
    #include <stdio.h>  /* librerias */
    #include <stdlib.h>
    #include <conio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main(void)
    {
    	char finLoop = 's';
    	int puntuacion = 0, posibilidad = 7, random=0, cont=0, i, x, z, size, opcion=0, value=20;
    	int fallos =0, aciertos=1;
        char secreta[10], c[10], jugador[20], rayas[15], guess, comodin;
        FILE *fp;
    
    	printf("Bienvenido al juego del ahorcado, por favor, introduce tu nombre: ");
        scanf("%s",jugador);
    
        srand((unsigned)time(0)); //Se usa funcion srand para generar numero aleatorio
        random =(rand()%10)+1;    //Se genera numero aleatorio y se pasa a la variable "random"
    
        for (i=0; i<=10; i++) // Limpiamos el array de cualquier residuo.
        {
           secreta[i] = '\0';
        }
        for (i=0; i<=10; i++) // Limpiamos el array de cualquier residuo.
        {
           rayas[i] = '\0';
        }
        fp = fopen("wordlist.txt","r"); //Abre el fichero para ser leido    
        if(fp==NULL) 
        {
           printf("Error: no se puede abrir el fichero.\n");       
           return 1;
        }
        else
        {
           while(fgets(c, 10, fp)!=NULL) 
           { 
             
              printf("String: %s", c);
              cont++;
              if (cont == random)
              {
               
               fgets(secreta,10,fp);
               goto etiqueta; // Usamos goto para que salte a la etiqueta una vez tener la palabra secreta
              }
           }
        etiqueta: //Etiqueta creada para el uso de goto
        fclose(fp);
        }
        
        size = (strlen(secreta)) - 1; //Obtenemos el tamaņo de la palabra
        printf("El size es: %d",size);
        system("cls");
        printf("1. Jugar al ahorcado.\n");
        printf("2. Reglas.\n");
        printf("3. Salir.\n");
        scanf("%d",&opcion);
        
        switch (opcion) 
        {
               case 1:
                    for (x=0; x<(size*2); x++)
                    {
                        rayas[x] = '_';
                        rayas[x+1] = ' ';
                        x++;
                    }   
                    printf("Palabra a resolver: %s",rayas);
                    while (fallos != '7')
                    {
                          printf("Introduce una letra: \n");
                          scanf("%c",&guess);
                          
                    }
                    printf("%s",rayas);
                    printf("%d",size);
                    scanf("%d",&x);
                    break;
               case 2: 
                    printf("Las reglas son las siguientes:\n");
                    printf("1. Por cada letra acertada, sumaras 2 puntos.\n");
                    printf("2. Por cada letra no acertada, restaras 1 punto.\n");
                    printf("3. Ganas si aciertas la palabra antes de cometer 7 fallos.\n");
                    printf("4. Si resuelves antes de gastar todas las oportunidades sumaras 10 puntos.\n");
                    break;
               case 3:
                    return 1;
                    break;
               default: 
                    printf("Opcion erronea, intentelo de nuevo.\n");
                        
                     
        }
    
    }

  8. #8
    Why am I a programmer? shoutatchickens's Avatar
    Join Date
    Mar 2008
    Posts
    45
    As a suggestion: try to break your code into workable parts and wirte them out into subroutines. That way the code will be easier for you to progress with as well as be a lot easier to read.

    What you could do is have a funciton that displays the current state of the word. After each guess you call this function and loop through each character of the array. On each iteration, compare the guess with the letter, if it matches print the letter, else print out a blank. Ask for another guess.
    One of the disadvantages of being a 22 year old RPG programmer is having to repeatedly explain to your friends that you don't make videogames for a living.

  9. #9
    Registered User
    Join Date
    Dec 2008
    Posts
    3
    Quote Originally Posted by shoutatchickens View Post
    As a suggestion: try to break your code into workable parts and wirte them out into subroutines. That way the code will be easier for you to progress with as well as be a lot easier to read.

    What you could do is have a funciton that displays the current state of the word. After each guess you call this function and loop through each character of the array. On each iteration, compare the guess with the letter, if it matches print the letter, else print out a blank. Ask for another guess.
    What do you mean by "current state of the word"?

    Thank you.

  10. #10
    Why am I a programmer? shoutatchickens's Avatar
    Join Date
    Mar 2008
    Posts
    45
    I mean which letters have been guessed and which ones are left.

    So you would take a for loop and compare and each time you would either print the letter for a correct match or a blank for a miss. If it is a miss you would also increase the miss count. Also you would decrease a count that starts off as the size of the word so when it hits 0 you know the user has won.
    One of the disadvantages of being a 22 year old RPG programmer is having to repeatedly explain to your friends that you don't make videogames for a living.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. need help using arrays ( simple hangman game)
    By skymoha in forum C Programming
    Replies: 2
    Last Post: 03-04-2009, 03:52 AM
  2. beach bar (sims type game)
    By DrKillPatient in forum Game Programming
    Replies: 1
    Last Post: 03-06-2006, 12:32 PM
  3. PC Game project requires c++ programmers
    By drallstars in forum Projects and Job Recruitment
    Replies: 2
    Last Post: 02-21-2006, 11:23 PM
  4. Using 'if' with char arrays or string objects
    By c++_n00b in forum C++ Programming
    Replies: 36
    Last Post: 06-06-2002, 09:04 PM
  5. Random Number problem in number guessing game...
    By -leech- in forum Windows Programming
    Replies: 8
    Last Post: 01-15-2002, 04:00 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21