Files
Informatik2-Praktikum-Worts…/Startcode/game.c
T
2026-10-27 12:24:34 +01:00

83 lines
2.9 KiB
C

#include "game.h"
#include <time.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RAND_TRIES_PER_WORD 1000
#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 wordCount, char **words)
{
// 1. Spielfeld vollständig mit EMPTY_CHAR initialisieren
for (int r = 0; r < MAX_SEARCH_FIELD_LEN; r++) {
for (int c = 0; c < MAX_SEARCH_FIELD_LEN; c++) {
salad[r][c] = EMPTY_CHAR;
}
}
int placedWordsCount = 0;
// 2. Jedes Wort aus der Wörterliste platzieren
for (unsigned int i = 0; i < wordCount; i++) {
if (words[i] == NULL) 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++) {
// 0 = Horizontal, 1 = Vertikal
int dir = rand() % 2;
int row, col;
if (dir == 0) { // Horizontal
row = rand() % MAX_SEARCH_FIELD_LEN;
col = rand() % (MAX_SEARCH_FIELD_LEN - len + 1);
} else { // Vertikal
row = rand() % (MAX_SEARCH_FIELD_LEN - len + 1);
col = rand() % MAX_SEARCH_FIELD_LEN;
}
// Prüfen, ob das Wort platziert werden kann (Kollisionsprüfung)
int canPlace = 1;
for (int k = 0; k < len; k++) {
int r = (dir == 1) ? (row + k) : row;
int c = (dir == 0) ? (col + k) : col;
// Feld muss noch leer sein oder exakt den gleichen Buchstaben enthalten
if (salad[r][c] != EMPTY_CHAR && salad[r][c] != words[i][k]) {
canPlace = 0;
break;
}
}
// Wenn die Position gültig ist, Buchstaben in das Spielfeld schreiben
if (canPlace) {
for (int k = 0; k < len; k++) {
int r = (dir == 1) ? (row + k) : row;
int c = (dir == 0) ? (col + k) : col;
salad[r][c] = words[i][k];
}
placedWordsCount++;
break; // Nächstes Wort verarbeiten
}
}
}
// 3. Verbleibende leere Felder (EMPTY_CHAR) 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;
}