Files
Informatik2-Praktikum-Worts…/Startcode/game.c
T
2026-10-30 01:08:54 +01:00

70 lines
2.7 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
// 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 wordCount, char words[][100], unsigned int seed)
{
// 1. Zufallsgenerator für deterministische Unit-Tests initialisieren
srand(seed);
// 2. Spielfeld initialisieren (memset füllt das gesamte 2D-Array sehr effizient mit EMPTY_CHAR)
memset(salad, EMPTY_CHAR, MAX_SEARCH_FIELD_LEN * MAX_SEARCH_FIELD_LEN);
int placedWordsCount = 0;
// 3. Jedes Wort aus der Wörterliste platzieren
for (unsigned int i = 0; i < wordCount; i++) {
int len = (int)strlen(words[i]);
if (len == 0 || len > MAX_SEARCH_FIELD_LEN) continue;
// Versuche bis zu MAX_RAND_TRIES_PER_WORD Mal, eine freie Position zu finden
for (int attempt = 0; attempt < MAX_RAND_TRIES_PER_WORD; attempt++) {
// Richtung und Deltas bestimmen (is_vert: 1=Vertikal, 0=Horizontal)
int is_vert = rand() % 2;
int dr = is_vert; // Zeilensprung (Delta Row): 1 wenn vertikal, sonst 0
int dc = !is_vert; // Spaltensprung (Delta Col): 1 wenn horizontal, sonst 0
// Startposition berechnen (verhindert automatisch Out-of-Bounds Fehler)
int row = rand() % (MAX_SEARCH_FIELD_LEN - (is_vert ? len - 1 : 0));
int col = rand() % (MAX_SEARCH_FIELD_LEN - (is_vert ? 0 : len - 1));
// Kollisionsprüfung
int canPlace = 1;
for (int k = 0; k < len; k++) {
char current = salad[row + k * dr][col + k * dc];
// Feld muss noch leer sein oder exakt den gleichen Buchstaben enthalten (Überschneidung)
if (current != EMPTY_CHAR && current != words[i][k]) {
canPlace = 0;
break;
}
}
// Wenn die Position gültig ist, Buchstaben eintragen
if (canPlace) {
for (int k = 0; k < len; k++) {
salad[row + k * dr][col + k * dc] = words[i][k];
}
placedWordsCount++;
break; // Erfolgreich platziert -> Schleife abbrechen, nächstes Wort verarbeiten
}
}
}
// 4. Verbleibende leere Felder mit Zufallsbuchstaben 'A'-'Z' auffüllen
for (int r = 0; r < MAX_SEARCH_FIELD_LEN; r++) {
for (int c = 0; c < MAX_SEARCH_FIELD_LEN; c++) {
if (salad[r][c] == EMPTY_CHAR) {
salad[r][c] = 'A' + (rand() % 26);
}
}
}
return placedWordsCount;
}