95 lines
2.9 KiB
C
95 lines
2.9 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)
|
|
{
|
|
srand((unsigned int)time(NULL));
|
|
|
|
// Spielfeld leeren
|
|
for (unsigned int i = 0; i < searchFieldLen; i++)
|
|
for (unsigned int j = 0; j < searchFieldLen; j++)
|
|
salad[i][j] = EMPTY_CHAR;
|
|
|
|
int placedCount = 0;
|
|
|
|
for (unsigned int w = 0; w < wordCount; w++) {
|
|
const char *word = words[w];
|
|
unsigned int len = strlen(word);
|
|
int placed = 0;
|
|
|
|
if (len > searchFieldLen)
|
|
continue; // Wort passt niemals ins Feld
|
|
|
|
for (int tries = 0; tries < MAX_RAND_TRIES_PER_WORD * searchFieldLen && !placed; tries++) {
|
|
int horizontal = rand() % 2;
|
|
|
|
unsigned int row = rand() % searchFieldLen;
|
|
unsigned int col = rand() % searchFieldLen;
|
|
|
|
// Stelle sicher, dass Wort im Spielfeld bleibt
|
|
if (horizontal) {
|
|
if (col + len > searchFieldLen) continue;
|
|
} else {
|
|
if (row + len > searchFieldLen) continue;
|
|
}
|
|
|
|
// Prüfen, ob Platz frei ist oder gleiche Buchstaben überlappen
|
|
int fits = 1;
|
|
for (unsigned int i = 0; i < len; i++) {
|
|
char c = horizontal ? salad[row][col + i] : salad[row + i][col];
|
|
if (c != EMPTY_CHAR && c != word[i]) {
|
|
fits = 0;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (!fits) continue;
|
|
|
|
// Wort einsetzen
|
|
for (unsigned int i = 0; i < len; i++) {
|
|
if (horizontal)
|
|
salad[row][col + i] = word[i];
|
|
else
|
|
salad[row + i][col] = word[i];
|
|
}
|
|
|
|
placed = 1;
|
|
placedCount++;
|
|
}
|
|
|
|
if (!placed) {
|
|
fprintf(stderr, "WARNUNG: Wort \"%s\" konnte nicht platziert werden.\n", word);
|
|
}
|
|
}
|
|
|
|
// Leere Felder auffüllen
|
|
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] = 'A' + (rand() % 26);
|
|
|
|
return placedCount;
|
|
}
|
|
|
|
// 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 i = 0; i < searchFieldLen; i++) {
|
|
for (unsigned int j = 0; j < searchFieldLen; j++) {
|
|
printf("%c ", salad[i][j]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
}
|