Files
I2-Pr/Wordsalat/game.c
T
2026-11-02 14:02:33 +01:00

78 lines
2.8 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)
{
// Initialize the salad with empty characters
for (unsigned int i = 0; i < searchFieldLen; i++) {
for (unsigned int j = 0; j < searchFieldLen; j++) {
salad[i][j] = EMPTY_CHAR;
}
}
// Seed the random number generator
srand((unsigned int)time(NULL));
// Place each word in the salad
for (unsigned int w = 0; w < wordCount; w++) {
const char *word = words[w];
unsigned int wordLen = strlen(word);
int placed = 0;
for (int tries = 0; tries < MAX_RAND_TRIES_PER_WORD && !placed; tries++) {
// Randomly choose orientation: 0 for horizontal, 1 for vertical
int orientation = rand() % 2;
unsigned int row, col;
if (orientation == 0) { // Horizontal
row = rand() % searchFieldLen;
col = rand() % (searchFieldLen - wordLen + 1);
// Check if the space is free
int canPlace = 1;
for (unsigned int k = 0; k < wordLen; k++) {
if (salad[row][col + k] != EMPTY_CHAR) {
canPlace = 0;
break;
}
}
if (canPlace) {
for (unsigned int k = 0; k < wordLen; k++) {
salad[row][col + k] = word[k];
}
placed = 1;
}
} else { // Vertical
row = rand() % (searchFieldLen - wordLen + 1);
col = rand() % searchFieldLen;
// Check if the space is free
int canPlace = 1;
for (unsigned int k = 0; k < wordLen; k++) {
if (salad[row + k][col] != EMPTY_CHAR) {
canPlace = 0;
break;
}
}
if (canPlace) {
for (unsigned int k = 0; k < wordLen; k++) {
salad[row + k][col] = word[k];
}
placed = 1;
}
}
}
if (!placed) {
return -1; // Failed to place the word after max tries
}
}