115 lines
3.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
//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 searchFieldLen, const char words[][MAX_WORD_LEN], unsigned int wordCount)
{// Länge der searchFieldLen wird in Main unter Salad size festgelegt (20)
srand((unsigned int)time(NULL)); // Seed für Zufallsgenerator
// Initialisiere das Spielfeld mit EMPTY_CHAR
for (unsigned int i = 0; i < searchFieldLen; ++i)
{
for (unsigned int j = 0; j < searchFieldLen; ++j)
{
salad[i][j] = ' ';
}
}
unsigned int placedWords = 0;
for (unsigned int word = 0; word < wordCount; ++word)
{
int placed = 0;
for (int tries = 0; tries < MAX_RAND_TRIES_PER_WORD && !placed; ++tries)
{
int direction = rand() % 2; // 1 = horizontal, 0 = vertical
int row = rand() % searchFieldLen;
int col = rand() % searchFieldLen;
int len = (int)strlen(words[word]);
if (direction == 1 && col + len <= searchFieldLen) // prüft ob das Wort horizontal in die Tabelle passt
{
int canPlace = 1;
for (int i = 0; i < len; ++i)
{
if (salad[row][col + i] != EMPTY_CHAR && salad[row][col + i] != words[word][i])
{
canPlace = 0;
break;
}
}
if (canPlace)
{
for (int i = 0; i < len; ++i)
salad[row][col + i] = words[word][i];
placed = 1;
}
}
else if (direction == 0 && row + len <= searchFieldLen) // vertical
{
int canPlace = 1;
for (int i = 0; i < len; ++i)
{
if (salad[row + i][col] != EMPTY_CHAR && salad[row + i][col] != words[word][i])
{
canPlace = 0;
break;
}
}
if (canPlace)
{
for (int i = 0; i < len; ++i)
salad[row + i][col] = words[word][i];
placed = 1;
}
}
}
if (placed)
placedWords++;
}
// Fülle leere Felder mit zufälligen Buchstaben
for (unsigned int i = 0; i < searchFieldLen; ++i)
{
for (unsigned int j = 0; j < searchFieldLen; ++j)
{
if (salad[i][j] == EMPTY_CHAR)
{
salad[i][j] = 'A' + rand() % 26;
}
}
}
return placedWords;
}
// Prints the word salad to console
void showWordSalad(const char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen)
{
for (unsigned int i = 0; i < searchFieldLen; ++i)
{
for (unsigned int j = 0; j < searchFieldLen; ++j)
{
printf("%c ", salad[i][j]);
}
printf("\n");
}
}