I tried to post this earlier, but it seems like my post was not properly submitted.
I'm trying to build a simple hangman game in C, but part of my code is breaking everything else i've done.
Here is the code, (i commented out the block that is breaking the program):
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#define MAX_WORDS 32
#define MAX_GUESSES 15
#define dir "/root/Desktop/WORDS"
int main() {
srand((unsigned int) time(NULL));
FILE *fp;
int charz;
int i;
int x = 0;
int guesses[MAX_GUESSES];
int lives_left = MAX_GUESSES;
int count = 0;
char ans[8];
char guess[5];
char buff[8];
char data_full[4096];
char *words[MAX_WORDS];
char *random_word[1];
struct stat stz;
stat(dir, &stz);
int r = rand();
if (stz.st_size > 0) {
fp = fopen(dir, "r");
fseek(fp, 0, SEEK_SET);
for (i = 0; i < stz.st_size; i++) {
charz = fgetc(fp);
if (charz == 10) {
strcat(data_full, " ");
} else {
sprintf(buff, "%c", charz);
strcat(data_full, buff);
}
}
fclose(fp);
words[0] = strtok(data_full, " ");
for (i = 0; i < MAX_WORDS; i++) {
if (!words[i]) {
break;
}
x++;
words[i+1] = strtok(NULL, " ");
}
random_word[0] = words[r%x];
printf("Random word: %s\n", random_word[0]);
printf("Would you like to play hangman? (Y/N): ");
fgets(ans, sizeof(ans), stdin);
strtok(ans, "\n");
if (strcmp(ans, "Y") == 0) {
for (i = 0; i < strlen(random_word[0]); i++) {
guesses[i] = 0;
}
printf("\nOkay, max guesses: %d | Word length is %zu\n", MAX_GUESSES, strlen(random_word[0]));
while (count != strlen(random_word[0])) {
printf("Guess: ");
fgets(guess, sizeof(guess), stdin);
strtok(guess, "\n");
// for (i = 0; i < strlen(random_word[0]); i++) {
// if (strcmp(guess, (char *) random_word[0][i]) == 0) {
// printf("Guessed one!");
// guesses[i] = 1;
// count++;
// } else {
// lives_left--; // Adding this line below to decrement counter.
// }
// }
lives_left--;
printf("\nLetters Guessed: ");
for (i = 0; i < strlen(random_word[0]); i++) {
printf("[%d]", guesses[i]);
}
printf("| Lives left: %d\n", lives_left);
if (lives_left == 0) {
printf("GAME OVER!");
break;
}
}
}
} else {
printf("No word list found");
}
return 0;
}
This is the output when i allow the commented code to run:
Code:
Random word: Banana
Would you like to play hangman? (Y/N): Y
Okay, max guesses: 15 | Word length is 6
Guess: n
Process finished with exit code 11
This is the output as is, with the code commented out:
Code:
Random word: Australia
Would you like to play hangman? (Y/N): Y
Okay, max guesses: 15 | Word length is 9
Guess: l
Letters Guessed: [0][0][0][0][0][0][0][0][0]| Lives left: 14
Guess:
The program seems to break as soon as it hits that block, and without it, the game just loops and does not check if a guess was correct.
Where might i have gone wrong here?