2025-11-03 16:24:32 +01:00

113 lines
3.8 KiB
C

#include "game.h"
#include <time.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RAND_TRIES_PER_WORD 10
#define EMPTY_CHAR 0
/* * Wörter aus der Wortliste zufällig horizontal oder vertikal platzieren
* restliche Felder mit zufälligen Buchstaben füllen */
typedef enum {
DIR_DOWN,
DIR_RIGHT,
DIR_FAILURE,
} check_dir_e;
static check_dir_e check_field(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN],
unsigned int searchFieldLen, const unsigned int word_len,
const int pos_x, const int pos_y)
{
const int random_direction = rand() % 2;
/* Check if direction right is usable*/
if (random_direction == 1) {
for (int i = 0; i < word_len; i++) {
if (pos_x + i >= searchFieldLen || salad[pos_y][pos_x + i] != '\0') {
break;
}
if (i == word_len - 1) {
return DIR_RIGHT;
}
}
}
/* Check if direction down is usable*/
for (int i = 0; i < word_len; i++) {
if (pos_y + i > searchFieldLen - 1 || salad[pos_y + i][pos_x] != '\0') {
break;
}
if (i == word_len - 1) {
return DIR_DOWN;
}
}
return DIR_FAILURE;
}
int createWordSalad(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN],
unsigned int searchFieldLen, const char words[][MAX_WORD_LEN],
unsigned int wordCount)
{
srand(time(NULL));
int pos_x;
int pos_y;
for (unsigned int y = 0; y < searchFieldLen; y++) {
for (unsigned int x = 0; x < searchFieldLen; x++) {
salad[y][x] = '\0';
}
}
int placedWords = 0;
unsigned int cnt;
for (cnt = 0; cnt < wordCount; cnt++) {
check_dir_e direction = DIR_FAILURE;
int tries = 0;
while (direction == DIR_FAILURE && tries < 1000) {
/* Generate new random position */
direction = DIR_FAILURE;
pos_x = rand() % searchFieldLen;
pos_y = rand() % searchFieldLen;
/* Check for valid fielddirection and create string */
direction = check_field(salad, searchFieldLen, strlen(words[cnt]), pos_x, pos_y);
/* Place words either down or right */
switch (direction) {
case DIR_DOWN:
for (int i = 0; i < strlen(words[cnt]); i++) {
salad[pos_y + i][pos_x] = words[cnt][i];
// printf("%d ; %d %s\n", (pos_y + i), pos_x, words[cnt]);
}
placedWords++;
break;
case DIR_RIGHT:
for (int i = 0; i < strlen(words[cnt]); i++) {
salad[pos_y][pos_x + i] = words[cnt][i];
// printf("%d ; %d %s\n", pos_y, (pos_x + i), words[cnt]);
}
placedWords++;
break;
case DIR_FAILURE:
break;
}
tries++;
/* If word was successfully placed break the while loop */
if (direction != DIR_FAILURE) {
break;
}
}
}
/* Fill the empty fields with random letters*/
for (unsigned int y = 0; y < searchFieldLen; y++) {
for (unsigned int x = 0; x < searchFieldLen; x++) {
if (salad[y][x] == '\0') {
salad[y][x] = 'A' + (rand() % 26);
}
}
}
return placedWords;
}
// Prints the word salad to console
void showWordSalad(const char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN],
unsigned int searchFieldLen)
{
for (unsigned int y = 0; y < searchFieldLen; y++) {
for (unsigned int x = 0; x < searchFieldLen; x++) {
printf("%c ", salad[y][x]);
}
printf("\n");
}
}