This is my hangman game code so far. I have a couple of concerns some of which are how do I mark the selected letters to be "SELECTED" so when the user chooses another letter, to not be able to use a letter that he has been used already. And also, I have a losing condition which if met, the game should break with a message however it never breaks.
I have already tried creating another array where I was going to be pushing all of the characters that have been selected. However, it did not work as I was getting errors as I cannot put characters in random positions as the previous slots wouldn't have been populated.
This is my main method:
int main() {
srand(time(NULL));
// the randomly selected word
char *word = generateStrings();
char sampleArray[strlen(word)];
sampleArray[strlen(word)] = '\0';
for (int i = 0; i < strlen(word); i++) {
sampleArray[i] = '_';
}
printf("%s\n", word);
char *printedWord = printWord(sampleArray, word);
return 0;
}
This is the method that basically does all the logic:
char *printWord(char sampleArray[], char *word) {
char letter;
int stopLoop=0;
int x = 0;
int winningSpree = 0;
int lost = 0;
while (1) {
system("@cls||clear"); // clear cmd window every itereation of the loop
printf("%s\n", word);
if (winningSpree==strlen(word)) {
printf("Congratulations! You've won!\n");
printf("%s", sampleArray);
break;
}
if (lost == 6) {
printf("You lost!\n");
printf("The word was: ", word, "\n");
break;
}
if (x == 0)
for (int i = 0; i < strlen(word); i++)
printf("_");
if (x > 0)
printf("Current stage of word: %s", sampleArray);
printf("\n");
printf("Give me a letter: ");
letter = askforinput();
printf("\n");
for (int j = 0; j < strlen(word); j++) {
if (word[j] == letter) {
sampleArray[j] = letter;
winningSpree++;
} else {
lost ++;
}
}
x++;
}
printf("\n");
return sampleArray;
}
And this is the method that asks for input:
// ask user for character input
char askforinput() {
char chosenLetter;
scanf("%c", &chosenLetter);
return chosenLetter;
}
Aucun commentaire:
Enregistrer un commentaire