2025-11-11 14:27:19 +01:00

118 lines
3.5 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
//TODO: Spiellogik implementieren:
/* * Wörter aus der Wortliste zufällig horizontal oder vertikal platzieren
* restliche Felder mit zufälligen Buchstaben füllen */
// Creates the word salad by placing words randomly and filling empty spaces
int createWordSalad(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen, const char words[][MAX_WORD_LEN], unsigned int wordCount)
{
//Wort für Wort dufrchgehen
//int position = 0;
srand(time(NULL));
int VerHor = 0;
int laenge = 0;
int maxPosition = 0;
int startPositionHor = 0;
int startPositionVer = 0;
int noFreigabe = 1;
int placedWords = 0;
int countTrys = 0;
//Jedes Wort einzeln durchgehen
for (int i = 0; i < wordCount; i++) {
laenge = strlen(words[i]);
//Vertikal oder Horizontal, Vertikal = 0; Horizontal = 1;
VerHor = rand() % 2;
//Maximale Startposition des Wortes bestimmen
maxPosition = searchFieldLen - laenge;
//Horizontal
if (VerHor) {
//Prüfen, ob die erforderlichen Felder frei sind, sonst erneute Positionsbestimmung
//Nach 10 vergeblichen Prüfungen wird abgebrochen
while (noFreigabe) {
countTrys++;
startPositionHor = rand() % (maxPosition + 1);
startPositionVer = rand() % searchFieldLen;
for (int j = 0; j < laenge; j++) {
if (salad[startPositionVer][startPositionHor + j] == EMPTY_CHAR) {
noFreigabe = 0;
}
else {
noFreigabe = 1;
break;
}
}
if (countTrys >= MAX_RAND_TRIES_PER_WORD)
break;
}
//Woerter in die leeren Felder eintragen
if (noFreigabe == 0) {
for (int j = 0; j < laenge; j++) {
salad[startPositionVer][startPositionHor + j] = words[i][j];
}
placedWords++;
countTrys = 0;
}
}
//Vertikal
else {
while (noFreigabe) {
countTrys++;
startPositionVer = rand() % (maxPosition + 1);
startPositionHor = rand() % searchFieldLen;
for (int j = 0; j < laenge; j++) {
if (salad[startPositionVer + j][startPositionHor] == EMPTY_CHAR) {
noFreigabe = 0;
}
else {
noFreigabe = 1;
break;
}
}
if (countTrys >= MAX_RAND_TRIES_PER_WORD)
break;
}
if (noFreigabe == 0) {
for (int j = 0; j < laenge; j++) {
salad[startPositionVer + j][startPositionHor] = words[i][j];
}
placedWords++;
countTrys = 0;
}
}
}
//Rest mit random Buchstaben auffüllen
for (int i = 0; i < searchFieldLen; i++) {
for (int j = 0; j < searchFieldLen; j++) {
if (salad[i][j] == EMPTY_CHAR)
salad[i][j] = ' ';// + (rand() % 26);
}
}
showWordSalad(salad, searchFieldLen);
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 (int i = 0; i < searchFieldLen; i++) {
for (int j = 0; j < searchFieldLen; j++) {
printf("%c", salad[i][j]);
}
printf("\n");
}
}