2013-03-16 2 views
0

Новичок на языке C, и я пытаюсь создать игру в палач. У меня есть следующий код:Hangman Game, используя проблемы C

int main(void) { 

    char userResponse;//This is the response from the user on rather they want to continue or not. 

    do { 
     startGame(); 

     printf("Do you want to continue (y or n): "); 
     scanf("%c", &userResponse); 

    } while(userResponse == 'y'); 

    return 0; 
} 

int startGame(void) { 

    int num_letters = 0; //length of word array 
    int count = 0; 
    int tries = 0; //total tries player has used 
    int correctGuesses = 0; //number of correct guesses 
    int correctLetter = 0; //flag to check if the letter guessed was correct. 
    int repeatLetter = 0; //flag to check if the letter guessed was already guessed before. 
    int randomWord = 1+(rand()%6); //setting a variable that will pick a word from the word array at random. 

    char word[] = {"spot", "physicist", "penny", "klingon", "bazinga", "continuum"}; // should these be all lower char or does it matter? 
    char guess; 
    char incorrectGuesses[5] = " "; // all the incorrect letters chosen by the player will be stored in this array. 
    char gameWord[num_letters]; //starts to fill out the word as the player guesses correctly 

    srand(time(NULL)); // Don't really understand this line but the interweb said I needed it. Can you tell me why? 

    num_letters = strlen(word); 

    gameWord[num_letters] = '\0'; 

    //This will show the player what letter they have typed incorrectly. 
    for(count = 0; count < num_letters; count++) 
     gameWord[count] = '-'; // This will display the length of the word represented with a "-". 

    printf("Welcome to Big Bang Hangman!\n\n"); 
    printf("Time to guess the word!"); 

    draw_hangman(tries); 

    while(tries < NUM_TRIES_ALLOWED) { //Player only gets 7 guesses. Found this on the interweb. 
     printf("Here is your word: %s\n", gameWord); 
     printf("Incorrect Letters: %s\n", incorrectGuesses); 
     printf("\nGuess a letter (and press 'Enter'): "); 
     fgets(&guess, sizeof(guess), stdin); 

     //This compares the current guess with the previous guesses so that you won't affect a turn if you pick the same incorrect letter. 
     for(count = 0; count < num_letters; count++) 
      if(guess == gameWord[count] || guess == incorrectGuesses[count]) { // If the player guess is equal to the size of the word or if its equal to the 
       repeatLetter = 1; 
       correctLetter = 1; 
       break; 
      } 

     if(repeatLetter == 0) // setting the flag back to 0 tells the compiler the game is over. 
     //Checks for matches in string 
      for(count = 0; count < num_letters; count++) { 
       if(guess == word[count]) { // can't understand why I'm getting this warrning. 
        gameWord[count] = guess; 
        correctGuesses++; 

        //if (correctGuesses == count) { 
         //printf("\n\nCONGRATULATIONS! You guessed the word %s!", gameWord); 
         //exit(0); 
        //} 
        if(correctGuesses == num_letters) { 
         printf("\n\nCONGRATULATIONS! You guessed the word %s!", gameWord); 
         exit(0); 
        } 

        correctLetter = 1; 
       } 
      } 

     if(correctLetter == 0) { 
      incorrectGuesses[tries] = guess; 
      tries++; 
     } 

     // reset both flags 
     repeatLetter = 0; 
     correctLetter = 0; 

     //startGame(); // Start the game over when the flag is reset. 
    } 

    printf("Sorry but you did not guess the word.\n"); 
    printf("The word is: %s\n\n", gameWord); 

    return 0; 
} 

Он выводит следующее:

Добро пожаловать в Big Bang палач!

Время угадывать слово!

___ 
| 
| 
| 
| 
| 
--- 
 
Here is your word: ---- 
Incorrect Letters: 

Guess a letter (and press 'Enter'): Here is your word: ---- 
Incorrect Letters: 

Последние две строки продолжают навсегда, пока я не остановить его. Я полностью потерян.
Любые советы были бы замечательными.

+0

'char guess;' - 'fgets (& guess, sizeof (guess), stdin);' <- 'fgets (buffer, size, stream)' хранит не более 'size - 1' байт из потока в буфер 'и добавляет 0 байт для завершения строки. С 'sizeof (guess) == 1', сколько байтов из ввода читает' fgets'? –

+0

Без 'srand (time (NULL));' вы должны получить такую ​​же случайную последовательность при каждом запуске программы – PSIAlt

ответ

0

У вас есть несколько проблем (и я действительно имею в виду) в вашем коде. Но давайте просто выбрать один

char guess; 

fgets(&guess, sizeof(guess), stdin); 

- это неправильный способ заставить пользователя ввести письмо. Возможно,

scanf("%c", &guess); 

будет работать лучше для вас.

Но на самом деле ваш подход ошибочен. Начните снова, напишите несколько строк кода, заставьте их работать, а затем запишите несколько. Вы написали множество кода, многие из которых ошибочны. Это не эффективный способ программирования.