#include "game.h" #include #include #include #define MAX_RAND_TRIES_PER_WORD 10 #define EMPTY_CHAR 0 // Fills array with EMPTY_CHAR, tries to place words into the salad and fills empty spaces with random letters. returns number of placed words or -1 if not all words could be placed. int createWordSalad(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen, const char words[][MAX_WORD_LEN], unsigned int wordCount) { 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; int wordsaborted = 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 if (tries == MAX_RAND_TRIES_PER_WORD) { printf("Abort trying to place the word -%s-\n", words[wordsplaced]); wordsplaced++; // skip this word and move to the next wordsaborted++; } } 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); } } } printf("Words aborted: %d\n", wordsaborted); return wordsaborted;; } // 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"); } }