forked from freudenreichan/info2Praktikum-Wortsalat
121 lines
3.0 KiB
C
121 lines
3.0 KiB
C
#include "game.h"
|
|
#include <time.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <stdio.h>
|
|
|
|
#define MAX_RAND_TRIES_PER_WORD 10
|
|
#define EMPTY_CHAR 0
|
|
|
|
int placeWord(int len, int column, int row,
|
|
char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN],
|
|
int searchFieldLen, const char* word, int axis);
|
|
|
|
// 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)
|
|
{
|
|
if (searchFieldLen == 0 || searchFieldLen > MAX_SEARCH_FIELD_LEN)
|
|
return 0;
|
|
|
|
int placedWords = 0;
|
|
|
|
srand(time(NULL));
|
|
|
|
// Spielfeld leeren:
|
|
for (int x = 0; x < searchFieldLen; x++)
|
|
for (int y = 0; y < searchFieldLen; y++)
|
|
salad[x][y] = EMPTY_CHAR;
|
|
|
|
|
|
// Wörter platzieren
|
|
for (int w = 0; w < wordCount; w++)
|
|
{
|
|
int wordlenght = strlen(words[w]); // Wortlänge festgelegt
|
|
|
|
if (wordlenght == 0 || wordlenght > searchFieldLen)
|
|
continue;
|
|
|
|
for (int attempts = 0;
|
|
attempts < MAX_RAND_TRIES_PER_WORD;
|
|
attempts++)
|
|
{
|
|
// Muss in for-Schleife sein damit immer neu erzeugt wird
|
|
int axis = rand() % 2;
|
|
int row = rand() % searchFieldLen;
|
|
int column = rand() % searchFieldLen;
|
|
|
|
int success = placeWord(
|
|
wordlenght, column, row, salad,
|
|
searchFieldLen, words[w], axis);
|
|
|
|
if (success)
|
|
{
|
|
placedWords++;
|
|
break;
|
|
}
|
|
|
|
printf("Platzierung zum %d. Mal fehlgeschlagen!\n",
|
|
attempts + 1);
|
|
}
|
|
}
|
|
|
|
//Fill empty spaces
|
|
for (int r = 0; r < searchFieldLen; r++)
|
|
{
|
|
for (int c = 0; c < searchFieldLen; c++)
|
|
{
|
|
if (salad[r][c] == EMPTY_CHAR)
|
|
{
|
|
salad[r][c] = 'A' + rand() % 26;
|
|
}
|
|
}
|
|
}
|
|
printf("%d placed" ,placedWords);
|
|
return placedWords;
|
|
}
|
|
|
|
|
|
int placeWord(int len, int column, int row,
|
|
char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN],
|
|
int searchFieldLen, const char* word, int axis)
|
|
{
|
|
// Available space check & word collision avoidance
|
|
for (int i = 0; i < len; i++)
|
|
{
|
|
if (axis == 0) // Horizontal
|
|
{
|
|
if (column + len > searchFieldLen ||
|
|
salad[row][column + i] != EMPTY_CHAR)
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
else // Vertical
|
|
{
|
|
if (row + len > searchFieldLen ||
|
|
salad[row + i][column] != EMPTY_CHAR)
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
//Write Word
|
|
for (int i = 0; i < len; i++)
|
|
{
|
|
if (axis == 0) // Horizontal
|
|
{
|
|
salad[row][column + i] = word[i];
|
|
}
|
|
else // Vertical
|
|
{
|
|
salad[row + i][column] = word[i];
|
|
}
|
|
}
|
|
|
|
return 1;
|
|
} |