Files
Wortsalat/Startcode/game.c
T
2026-11-03 09:03:13 +01:00

133 lines
3.2 KiB
C

#include "game.h"
#include "game.h"
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_ATTEMPTS 100
#define EMPTY_CHAR '\0'
typedef enum
{
HORIZONTAL,
VERTICAL
} Direction;
int createWordSalad(
char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN],
unsigned int searchFieldLen,
const char words[][MAX_WORD_LEN],
unsigned int wordCount)
{
/* Spielfeldgroesse pruefen */
if (searchFieldLen == 0 ||
searchFieldLen > MAX_SEARCH_FIELD_LEN)
{
return 0;
}
int placedWords = 0;
/* Alle Felder initialisieren */
for (unsigned int i = 0; i < searchFieldLen; i++)
{
for (unsigned int j = 0; j < searchFieldLen; j++)
{
salad[i][j] = EMPTY_CHAR;
}
}
/* Richtungsvektoren */
int dx[] = {1, 0};
int dy[] = {0, 1};
/* Alle Woerter durchlaufen */
for (unsigned int w = 0; w < wordCount; w++)
{
size_t wordLen = strlen(words[w]);
/* Leere oder zu lange Woerter ueberspringen */
if (wordLen == 0 || wordLen > searchFieldLen)
{
continue;
}
int placed = 0;
int attempts = 0;
while (!placed && attempts < MAX_ATTEMPTS)
{
attempts++;
/* Zufallsrichtung bestimmen */
Direction dir = rand() % 2;
unsigned int row;
unsigned int col;
/* Zufallsposition so waehlen, dass das Wort hineinpasst */
if (dir == HORIZONTAL)
{
row = rand() % searchFieldLen;
col = rand() % (searchFieldLen - wordLen + 1);
}
else
{
row = rand() % (searchFieldLen - wordLen + 1);
col = rand() % searchFieldLen;
}
int collision = 0;
/* Pruefen, ob die Position geeignet ist */
for (size_t i = 0; i < wordLen; i++)
{
unsigned int z = row + dy[dir] * i;
unsigned int s = col + dx[dir] * i;
char letter =
(char)toupper((unsigned char)words[w][i]);
if (salad[z][s] != EMPTY_CHAR &&
salad[z][s] != letter)
{
collision = 1;
break;
}
}
/* Wenn keine Kollision besteht, Wort eintragen */
if (!collision)
{
for (size_t i = 0; i < wordLen; i++)
{
unsigned int z = row + dy[dir] * i;
unsigned int s = col + dx[dir] * i;
salad[z][s] =
(char)toupper((unsigned char)words[w][i]);
}
placed = 1;
placedWords++;
}
}
}
/* Leere Felder mit zufaelligen Buchstaben fuellen */
for (unsigned int i = 0; i < searchFieldLen; i++)
{
for (unsigned int j = 0; j < searchFieldLen; j++)
{
if (salad[i][j] == EMPTY_CHAR)
{
salad[i][j] = (char)('A' + rand() % 26);
}
}
}
return placedWords;
}