Files
info2Praktikum-Wortsalat/Startcode/game.c
T
2026-10-26 12:32:21 +01:00

126 lines
3.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
typedef enum{
HORIZONTAL,
VERTICAL
} Richtung;
//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
// Buchstabengitter Koordinaten Seitenlänge die Wörter, der Buchstabe Anzahl der Wörter
int createWordSalad(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen, const char words[][MAX_WORD_LEN], unsigned int wordCount)
{
for(int i = 0; i < searchFieldLen; i++)
{
for(int j = 0; j < searchFieldLen; j++)
{
salad[i][j] = EMPTY_CHAR;
}
}
int placeWords = 0;
for(int i = 0; i < wordCount; i++)
{
int Spalte;
int Zeile;
int WORD_LEN = strlen(words[i]); //Buchstaben zählen
int platziert = 0;
for(int try = 0; try < MAX_RAND_TRIES_PER_WORD; try++) // Max 10 Versuche pro Wort
{
Richtung dir = rand() % 2;
int passt = 1;
if(dir == HORIZONTAL)
{
Spalte = rand() % searchFieldLen;
Zeile = rand() % searchFieldLen;
if(Spalte + WORD_LEN <= searchFieldLen) // Prüft auf Border
{
for(int k = 0; k < WORD_LEN; k++)
{
if(salad[Zeile][Spalte+k] != EMPTY_CHAR) // Koalisionsprüfung
{
passt = 0; //Kollision gefunden
break;
}
}
if(passt == 1)
{
for(int s = 0; s < WORD_LEN; s++)
{
salad[Zeile][Spalte + s] = words[i][s]; // Das Wort eintragen in einer Zeile
}
platziert = 1;
break; // Das Wort kann eingetragen werden, keine Kollision
}
}
}
else // Vertikal
{
Spalte = rand() % searchFieldLen;
Zeile = rand() % searchFieldLen;
if(Zeile + WORD_LEN <= searchFieldLen)
{
int passt = 1;
for(int k = 0; k < WORD_LEN; k++)
{
if(salad[Zeile+k][Spalte] != EMPTY_CHAR)
{
passt = 0; //Kollision gefunden
break;
}
}
if(passt == 1)
{
for(int z = 0; z < WORD_LEN; z++)
{
salad[Zeile + z][Spalte] = words[i][z]; // // Das Wort eintragen in einer Spalte
}
platziert = 1;
break; // Das Wort kann eingetragen werden, keine Kollision
}
}
}
}
if(platziert == 1)
{
placeWords++;
}
}
for(int i = 0; i < searchFieldLen; i++)
{
for(int j = 0; j < searchFieldLen; j++)
{
if(salad[i][j] == EMPTY_CHAR) // Nur wenn Feld noch frei ist, dann mit random Buchstaben belegen
{
salad[i][j] = 'A' + (rand() % 26);
}
}
}
return placeWords;
}