#include "game.h" #include #include #include #define MAX_RAND_TRIES_PER_WORD 10 #define EMPTY_CHAR 0 // 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) { 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; } // 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"); } }