2025-11-04 11:49:18 +01:00

116 lines
3.8 KiB
C

#include "game.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
int createWordSalad(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen, const char words[][MAX_WORD_LEN], unsigned int wordCount)
{
//testing variables
int MAX_RAND_TRIES_PER_WORD = 10;
int EMPTY_CHAR = 0;
//end of testing variables
memset(salad, EMPTY_CHAR, MAX_SEARCH_FIELD_LEN * MAX_SEARCH_FIELD_LEN * sizeof(salad[0][0]));
int line = 0;
int column = 0;
int wordsplaced = 0;
while (wordsplaced < wordCount) {
int direction = rand() % 2; // 0 = horizontal, 1 = vertical
int wordlen = strlen(words[wordsplaced]);
int placed = 0;
int tries = 0;
while (!placed && tries < MAX_RAND_TRIES_PER_WORD) {
if (direction == 0) { // horizontal
if (wordlen <= searchFieldLen) {
column = rand() % (searchFieldLen - wordlen + 1);
line = rand() % searchFieldLen;
int canPlace = 1;
for (int i = 0; i < wordlen; i++) {
if (salad[line][column + i] != EMPTY_CHAR && salad[line][column + i] != words[wordsplaced][i]) {
canPlace = 0;
break;
}
}
if (canPlace) {
for (int i = 0; i < wordlen; i++) {
salad[line][column + i] = words[wordsplaced][i];
}
placed = 1;
}
}
} else { // vertical
if (wordlen <= searchFieldLen) {
line = rand() % (searchFieldLen - wordlen + 1);
column = rand() % searchFieldLen;
int canPlace = 1;
for (int i = 0; i < wordlen; i++) {
if (salad[line + i][column] != EMPTY_CHAR && salad[line + i][column] != words[wordsplaced][i]) {
canPlace = 0;
break;
}
}
if (canPlace) {
for (int i = 0; i < wordlen; i++) {
salad[line + i][column] = words[wordsplaced][i];
}
placed = 1;
}
}
}
tries++;
}
if (placed) {
wordsplaced++;
} else {
// Could not place the word after max tries
return -1;
}
}
for (int i = 0; i < searchFieldLen; i++) { // replaces 0 with random letters
for (int j = 0; j < searchFieldLen; j++) {
if (salad[i][j] == EMPTY_CHAR) {
salad[i][j] = 'A' + (rand() % 26);
}
}
}
return wordsplaced;
}
int main(void) {
int SALAD_SIZE = 10;
char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN];
unsigned int searchFieldLen = SALAD_SIZE;
const char words[][MAX_WORD_LEN] = {"TEST", "WORD", "DEINEMUDDA"}; // Add your words here
unsigned int wordCount = 3; // Update this based on number of words
int placedWords;
placedWords = createWordSalad(salad, searchFieldLen, words, wordCount);
for (unsigned int i = 0; i < searchFieldLen; i++) { // code von showWordSalad
for (unsigned int j = 0; j < searchFieldLen; j++) {
printf("%c ", salad[i][j]);
}
printf("\n");
}
//code for main.c:
if (placedWords == wordCount) {
printf("All words placed successfully.\n");
} else {
printf("Could not place all words. Placed %d out of %d words.\n", placedWords, wordCount);
}
return 0;
}