#include <time.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>
#include <windows.h>
int main() {
for(;;) {
FILE *file = fopen("words.txt", "r");
int amount = 1000;
char part[amount];
long wc = 0;
while(fgets(part, sizeof part, file) != NULL) {
++wc;
}
char parts[amount][amount];
srand((unsigned) time(NULL));
for(int i = 0; i < amount; i++) {
rewind(file);
int sel = rand() % wc + 1;
for(int j = 0; j < sel; j++) {
fgets(part, sizeof part, file);
}
strcpy(parts[i], part);
}
char *string = parts[rand() % amount];
int length = strlen(string);
int mask[length];
for(int i = 0; i < length; i++) {
mask[i] = 0;
}
int tries = 6;
int gameend = 0;
while(gameend == 0) {
system("cls");
for(int i = 0; i < length; i++) {
if(mask[i] == 0) {
printf("_");
} else {
printf("%c", string[i]);
}
}
printf("\ntries: %i", tries);
printf("\n_____");
printf("\n |");
if(tries == 5) {
printf("\n o");
} else if(tries == 4) {
printf("\n o");
printf("\n |");
} else if(tries == 3) {
printf("\n o");
printf("\n /|");
} else if(tries == 2) {
printf("\n o");
printf("\n /|\\");
} else if(tries == 1) {
printf("\n o");
printf("\n /|\\");
printf("\n /");
} else if(tries == 0) {
printf("\n o");
printf("\n /|\\");
printf("\n /\\");
}
char c;
scanf("%c", &c);
int acorrect = 0;
int bcorrect = 1;
for(int i = 0; i < length; i++) {
if(string[i] == c) {
mask[i] = 1;
acorrect = 1;
}
if(mask[i] == 0) {
bcorrect = 0;
}
}
gameend = bcorrect;
if(acorrect == 0) {
if(isalpha(c)) {
if(tries > 0) {
tries -= 1;
} else {
gameend = 1;
}
}
}
}
system("cls");
if(tries > 0) {
printf("you won! the word was: %s", string);
} else {
printf("you LOST! the word was: %s", string);
}
sleep(1);
}
}
If you can tell I'm quite new to C so any help will be appreciated.
This is a game about hangman, you guess words that are located within words.txt
words.txt is formatted like this:
word1
word2
word3
word4
word5
https://gyazo.com/8777d7176802eca1f9347143ee05c894
As you see from this video, it adds an extra underscore but removes it once the screen is cleared. The issue does not appear on the second word.