cordle/src/words.c

84 lines
1.9 KiB
C
Raw Normal View History

2025-10-06 13:58:25 +00:00
//
// Created by Gregory Gauthier on 06/10/2025.
//
/* words.c - Word list management implementation */
#include "../include/words.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
/* Convert string to uppercase */
2025-12-17 09:28:00 +00:00
void to_upper(char *str) {
2025-10-06 13:58:25 +00:00
int i;
for (i = 0; str[i]; i++) {
str[i] = toupper(str[i]);
}
}
/* Load words from file */
2025-12-17 09:28:00 +00:00
int load_words(GameState *game, const char *filename) {
FILE *file;
2025-10-06 13:58:25 +00:00
char filepath[MAX_FILENAME];
char line[32];
char word[WORD_LENGTH + 1];
int len;
/* Construct file path */
sprintf(filepath, "wordlists/%s", filename);
file = fopen(filepath, "r");
if (!file) {
/* Try without wordlists/ prefix */
file = fopen(filename, "r");
if (!file) {
return 0;
}
}
game->word_count = 0;
while (fgets(line, sizeof(line), file) && game->word_count < MAX_WORDS) {
/* Remove newline and whitespace */
len = strlen(line);
2025-12-17 09:28:00 +00:00
while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r' || line[len - 1] == ' ')) {
2025-10-06 13:58:25 +00:00
line[--len] = '\0';
}
if (len == WORD_LENGTH) {
strcpy(word, line);
to_upper(word);
strcpy(game->words[game->word_count], word);
game->word_count++;
}
}
fclose(file);
if (game->word_count == 0) {
return 0;
}
/* Select random target word */
2025-12-17 09:28:00 +00:00
srand((unsigned int) time(NULL));
2025-10-06 13:58:25 +00:00
strcpy(game->target_word, game->words[rand() % game->word_count]);
return 1;
}
/* Check if word exists in word list */
2025-12-17 09:28:00 +00:00
int is_valid_word(GameState *game, const char *word) {
2025-10-06 13:58:25 +00:00
int i;
char upper_word[WORD_LENGTH + 1];
strcpy(upper_word, word);
to_upper(upper_word);
for (i = 0; i < game->word_count; i++) {
if (strcmp(game->words[i], upper_word) == 0) {
return 1;
}
}
return 0;
}