2025-10-21 06:58:43 +02:00

129 lines
3.6 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)
// {
// }
// // Prints the word salad to console
// void showWordSalad(const char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen)
// {
// }
// Hàm tạo ngẫu nhiên một chữ cái in hoa
char randomLetter()
{
return 'A' + rand() % 26;
}
// Hàm chính: Tạo trò chơi word salad
int createWordSalad(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN],
unsigned int searchFieldLen,
const char words[][MAX_WORD_LEN],
unsigned int wordCount)
{
// 1. Khởi tạo lưới trống
for (unsigned int i = 0; i < searchFieldLen; i++)
{
for (unsigned int j = 0; j < searchFieldLen; j++)
{
salad[i][j] = EMPTY_CHAR;
}
}
srand((unsigned int)time(NULL));
// 2. Đặt từng từ vào lưới
for (unsigned int w = 0; w < wordCount; w++)
{
const char *word = words[w];
size_t len = strlen(word);
if (len > searchFieldLen)
continue; // Bỏ qua nếu từ quá dài
int placed = 0;
for (int attempt = 0; attempt < MAX_RAND_TRIES_PER_WORD && !placed; attempt++)
{
int dir = rand() % 2; // 0 = ngang, 1 = dọc
int row = rand() % searchFieldLen;
int col = rand() % searchFieldLen;
// Kiểm tra xem từ có vừa vị trí không
if (dir == 0 && col + len <= searchFieldLen)
{
// Kiểm tra xem có bị đè chữ khác không
int ok = 1;
for (size_t i = 0; i < len; i++)
{
if (salad[row][col + i] != EMPTY_CHAR && salad[row][col + i] != word[i])
{
ok = 0;
break;
}
}
if (ok)
{
for (size_t i = 0; i < len; i++)
salad[row][col + i] = word[i];
placed = 1;
}
}
else if (dir == 1 && row + len <= searchFieldLen)
{
int ok = 1;
for (size_t i = 0; i < len; i++)
{
if (salad[row + i][col] != EMPTY_CHAR && salad[row + i][col] != word[i])
{
ok = 0;
break;
}
}
if (ok)
{
for (size_t i = 0; i < len; i++)
salad[row + i][col] = word[i];
placed = 1;
}
}
}
}
// 3. Điền ký tự ngẫu nhiên vào các ô trống
for (unsigned int i = 0; i < searchFieldLen; i++)
{
for (unsigned int j = 0; j < searchFieldLen; j++)
{
if (salad[i][j] == EMPTY_CHAR)
salad[i][j] = randomLetter();
}
}
return 0; // 0 = thành công
}
// Hàm in lưới ra màn hình
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");
}
}