Files
Info-2-Praktikum/Startcode/game.c
T
2026-10-20 15:51:14 +02:00

102 lines
2.9 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)
{
if (salad == NULL || words == NULL || searchFieldLen == 0){
return 0;
}
//1. Spielfeld mit Nullen (Leerzeichen/leeren Zellen) Vorinitialisieren
for(unsigned int i = 0; i< searchFieldLen; i++){
for(unsigned int j = 0; j < searchFieldLen; j++)
{
salad[i][j] = '\0';
}
}
//Zufallszahlengenerator initialisation
srand((unsigned int)time(NULL));
unsigned int sucessfullyPlaced = 0;
//2. Jedes Wort einzeln im Gitter Plazieren
for(unsigned int w = 0; w < wordCount; w++)
{
int len = (int)strlen(words[w]);
if((unsigned int)len > searchFieldLen){
//wort ist zu lang für das Suchfeld
continue;
}
int placed = 0;
int attempts = 0;
//MAximum Versuche, um eine passende Position zu finden, um ENdlosshleifen zu vermeiden
while(!placed && attempts < 5000){
attempts++;
int direction = rand() %2; // 0 = horizontal, 1 = vertical
int row = 0;
int col = 0;
if(direction == 0) // horizontal
{
row = rand() % searchFieldLen;
col = rand() % (searchFieldLen - len + 1);
}
else // vertical
{
row = rand() % (searchFieldLen - len + 1);
col = rand() % searchFieldLen;
}
// KOllisionsprüfung
int collision = 0;
for(int i = 0; i < len; i++)
{
int r = row + (direction == 1? i : 0);
int c = col + (direction == 0 ? i : 0);
if(salad[r][c] != '\0' && salad[r][c] != words[w][i]){
collision = 1;
break;
}
}
//wenn keine kollision vorliegt, Wort ins Gitter schreiben
if(!collision){
for(int i = 0; i < len; i++){
int r = row + (direction == 1 ? i : 0);
int c = col + (direction == 0 ? i : 0);
salad[r][c] = words[w][i];
}
sucessfullyPlaced++;
placed = 1;
}
}
}
// Alle restlichen (leeren) Felder mit zufäalligen Großbuchstaben ('A' - 'Z') auffullen
for(unsigned int i = 0; i < searchFieldLen; i++){
for(unsigned int j = 0; j < searchFieldLen; j++)
{
if(salad[i][j] == '\0'){
salad[i][j] = (char)('A' + (rand() % 26));
}
}
}
return (int)sucessfullyPlaced;
}