optimisation et commentaires

This commit is contained in:
Hugo BRANCO-GOMES 2024-10-25 15:45:38 +02:00
parent 0ac6119bb3
commit f4de9cf8bd

25
pendu.c
View File

@ -28,6 +28,7 @@ void display_hangman(int tries) {
} }
// Function to randomly choose words and concatenate them to create a puzzle word // Function to randomly choose words and concatenate them to create a puzzle word
// Ensures that the maximum word length is respected by avoiding overflow with strncat
void choose_words(char *chosen_word, int max_length) { void choose_words(char *chosen_word, int max_length) {
int total_length = 0, used[MAX_WORDS] = {0}, word_index; int total_length = 0, used[MAX_WORDS] = {0}, word_index;
chosen_word[0] = '\0'; chosen_word[0] = '\0';
@ -35,24 +36,34 @@ void choose_words(char *chosen_word, int max_length) {
// Select words until the maximum word length is reached or exceeded // Select words until the maximum word length is reached or exceeded
while (total_length < max_length) { while (total_length < max_length) {
word_index = rand() % MAX_WORDS; word_index = rand() % MAX_WORDS;
if (!used[word_index] && total_length + strlen(words[word_index]) + (total_length > 0 ? 1 : 0) <= max_length) { int word_length = strlen(words[word_index]);
if (total_length > 0) { strcat(chosen_word, " "); total_length++; } int additional_space = (total_length > 0 ? 1 : 0); // Space between words if needed
strcat(chosen_word, words[word_index]);
total_length += strlen(words[word_index]); // Ensure word fits within the remaining length
if (!used[word_index] && total_length + word_length + additional_space <= max_length) {
if (additional_space > 0) {
strncat(chosen_word, " ", max_length - total_length - 1);
total_length++;
}
strncat(chosen_word, words[word_index], max_length - total_length - 1);
total_length += word_length;
used[word_index] = 1; used[word_index] = 1;
if (total_length == max_length) break;
} }
// Check if all words that could fit are used // Break if no other words can fit in the remaining space
int all_used = 1; int all_used = 1;
for (int i = 0; i < MAX_WORDS; i++) { for (int i = 0; i < MAX_WORDS; i++) {
if (!used[i] && total_length + strlen(words[i]) + 1 <= max_length) { all_used = 0; break; } if (!used[i] && total_length + strlen(words[i]) + 1 <= max_length) {
all_used = 0;
break;
}
} }
if (all_used) break; if (all_used) break;
} }
} }
// Function to play the hangman game // Function to play the hangman game
// Displays the game state and checks if each guess is correct or already revealed
void play_game(const char *chosen_word, int word_length, int letters_to_guess) { void play_game(const char *chosen_word, int word_length, int letters_to_guess) {
char guessed[word_length + 1]; char guessed[word_length + 1];
int tries = 0, guessed_correctly = 0; int tries = 0, guessed_correctly = 0;