forked from freudenreichan/info2Praktikum-Wortsalat
93 lines
2.7 KiB
C
93 lines
2.7 KiB
C
#include "game.h"
|
|
#include <time.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <ctype.h>
|
|
|
|
#define MAX_RAND_TRIES_PER_WORD 10
|
|
#define EMPTY_CHAR 0
|
|
|
|
typedef enum { HORIZONTAL, VERTICAL } Direction;
|
|
|
|
// Versucht, ein einzelnes Wort an einer zufälligen Position zu platzieren; gibt 1 bei Erfolg zurück, sonst 0
|
|
static int placeWord(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen, const char *word)
|
|
{
|
|
unsigned int wordLen = strlen(word);
|
|
|
|
if(wordLen == 0 || wordLen > searchFieldLen)
|
|
return 0;
|
|
|
|
for(int try = 0; try < MAX_RAND_TRIES_PER_WORD; try++)
|
|
{
|
|
Direction dir = rand() % 2;
|
|
unsigned int row, col;
|
|
|
|
// Startposition so wählen, dass das Wort ins Spielfeld passt
|
|
if(dir == HORIZONTAL)
|
|
{
|
|
row = rand() % searchFieldLen;
|
|
col = rand() % (searchFieldLen - wordLen + 1);
|
|
}
|
|
else
|
|
{
|
|
row = rand() % (searchFieldLen - wordLen + 1);
|
|
col = rand() % searchFieldLen;
|
|
}
|
|
|
|
// Prüfen, ob alle benötigten Felder noch leer sind
|
|
int isFree = 1;
|
|
for(unsigned int i = 0; i < wordLen; i++)
|
|
{
|
|
if(dir == HORIZONTAL && salad[row][col + i] != EMPTY_CHAR)
|
|
isFree = 0;
|
|
if(dir == VERTICAL && salad[row + i][col] != EMPTY_CHAR)
|
|
isFree = 0;
|
|
}
|
|
|
|
if(isFree)
|
|
{
|
|
for(unsigned int i = 0; i < wordLen; i++)
|
|
{
|
|
if(dir == HORIZONTAL)
|
|
salad[row][col + i] = toupper(word[i]);
|
|
else
|
|
salad[row + i][col] = toupper(word[i]);
|
|
}
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
// Erstellt den Wortsalat: platziert die Wörter zufällig und füllt leere Felder auf
|
|
int createWordSalad(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen, const char words[][MAX_WORD_LEN], unsigned int wordCount)
|
|
{
|
|
static int isSeeded = 0;
|
|
int placedWords = 0;
|
|
|
|
// Zufallszahlengenerator nur einmal initialisieren
|
|
if(!isSeeded)
|
|
{
|
|
srand(time(NULL));
|
|
isSeeded = 1;
|
|
}
|
|
|
|
// Alle Felder als leer markieren
|
|
for(unsigned int i = 0; i < searchFieldLen; i++)
|
|
for(unsigned int j = 0; j < searchFieldLen; j++)
|
|
salad[i][j] = EMPTY_CHAR;
|
|
|
|
// Wörter platzieren
|
|
for(unsigned int i = 0; i < wordCount; i++)
|
|
placedWords += placeWord(salad, searchFieldLen, words[i]);
|
|
|
|
// Restliche Felder mit zufälligen Buchstaben füllen
|
|
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;
|
|
}
|