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

67 lines
2.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
// 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)
{
// 1. Spielfeld initialisieren (memset ist kürzer und effizienter als Schleifen)
memset(salad, EMPTY_CHAR, MAX_SEARCH_FIELD_LEN * MAX_SEARCH_FIELD_LEN);
int placedWordsCount = 0;
// 2. Jedes Wort aus der Wörterliste platzieren
for (unsigned int i = 0; i < wordCount; i++) {
if (!words[i]) continue;
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 Out-of-Bounds)
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];
if (current != EMPTY_CHAR && current != words[i][k]) {
canPlace = 0;
break;
}
}
// Wenn die Position gültig ist, Wort eintragen
if (canPlace) {
for (int k = 0; k < len; k++) {
salad[row + k * dr][col + k * dc] = words[i][k];
}
placedWordsCount++;
break; // Erfolgreich platziert -> Nächstes Wort
}
}
}
// 3. Verbleibende leere Felder mit Zufallsbuchstaben 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;
}