63 lines
2.1 KiB
C
63 lines
2.1 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
|
|
|
|
int createWordSalad(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int wordCount, char words[][100], unsigned int gridSize)
|
|
{
|
|
// 1. Komplettes Array sicherheitshalber mit EMPTY_CHAR leeren
|
|
memset(salad, EMPTY_CHAR, MAX_SEARCH_FIELD_LEN * MAX_SEARCH_FIELD_LEN);
|
|
|
|
int placedWordsCount = 0;
|
|
|
|
// 2. Wörter platzieren
|
|
for (unsigned int i = 0; i < wordCount; i++) {
|
|
int len = (int)strlen(words[i]);
|
|
|
|
// WICHTIG: Wenn das Wort länger ist als das eigentliche Spielfeld (gridSize), direkt überspringen!
|
|
if (len == 0 || len > gridSize) continue;
|
|
|
|
// Versuche eine freie Position zu finden
|
|
for (int attempt = 0; attempt < MAX_RAND_TRIES_PER_WORD; attempt++) {
|
|
|
|
int is_vert = rand() % 2;
|
|
int dr = is_vert;
|
|
int dc = !is_vert;
|
|
|
|
// Zufällige Position INNERHALB der gridSize wählen (nicht mehr 100x100!)
|
|
int row = rand() % (gridSize - (is_vert ? len - 1 : 0));
|
|
int col = rand() % (gridSize - (is_vert ? 0 : len - 1));
|
|
|
|
int canPlace = 1;
|
|
for (int k = 0; k < len; k++) {
|
|
char current = salad[row + k * dr][col + k * dc];
|
|
if (current != EMPTY_CHAR && current != words[i][k]) {
|
|
canPlace = 0;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (canPlace) {
|
|
for (int k = 0; k < len; k++) {
|
|
salad[row + k * dr][col + k * dc] = words[i][k];
|
|
}
|
|
placedWordsCount++;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 3. Verbleibende leere Felder (nur innerhalb der gridSize!) mit Zufallsbuchstaben auffüllen
|
|
for (unsigned int r = 0; r < gridSize; r++) {
|
|
for (unsigned int c = 0; c < gridSize; c++) {
|
|
if (salad[r][c] == EMPTY_CHAR) {
|
|
salad[r][c] = 'A' + (rand() % 26);
|
|
}
|
|
}
|
|
}
|
|
|
|
return placedWordsCount;
|
|
} |