#include "game.h" #include #include #include #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 */ enum PlaceDirection { HORIZONTAL, VERTICAL }; bool canPlaceWord(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen, const char *word, unsigned int wordLength, unsigned int row, unsigned int col, PlaceDirection dir) { if (dir == HORIZONTAL) // HORIZONTAL { if (col + wordLength > searchFieldLen) return false; for (unsigned int i = 0; i < wordLength; i++) { char current = salad[row][col + i]; if (current != EMPTY_CHAR && current != word[i]) return false; } } else // VERTICAL { if (row + wordLength > searchFieldLen) return false; for (unsigned int i = 0; i < wordLength; i++) { char current = salad[row + i][col]; if (current != EMPTY_CHAR && current != word[i]) return false; } } return true; } // write word in the grid void writeWord(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], const char *word, unsigned int wordLength, unsigned int row, unsigned int col, PlaceDirection dir) { for (unsigned int i = 0; i < wordLength; i++) { if (dir == HORIZONTAL) { salad[row][col + i] = word[i]; } else { salad[row + i][col] = word[i]; } } } // try to place a word with a return value bool placeWordAttempt(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen, const char *word, unsigned int wordLength, PlaceDirection dir) { for (int attempt = 0; attempt < MAX_RAND_TRIES_PER_WORD; attempt++) { unsigned int row, col; if (dir == HORIZONTAL) { row = rand() % searchFieldLen; col = rand() % (searchFieldLen - wordLength + 1); } else // VERTICAL { row = rand() % (searchFieldLen - wordLength + 1); col = rand() % searchFieldLen; } if (canPlaceWord(salad, searchFieldLen, word, wordLength, row, col, dir)) { writeWord(salad, word, wordLength, row, col, dir); return true; } } return false; // could not be placed after MAX_RAND_TRIES_PER_WORD tries } // 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) { // place words randomly in salad array for (unsigned int i = 0; i < wordCount; i++) { const char *word = words[i]; unsigned int len = strlen(word); PlaceDirection dir = (rand() % 2 == 0) ? HORIZONTAL : VERTICAL; placeWordAttempt(salad, searchFieldLen, word, len, dir); } // fill up empty fields for (unsigned int r = 0; r < searchFieldLen; r++) { for (unsigned int c = 0; c < searchFieldLen; c++) { if (salad[r][c] == EMPTY_CHAR) { salad[r][c] = 'A' + (rand() % 26); } } } return 0; }