Skip to content

Instantly share code, notes, and snippets.

@nandakoryaaa
Created June 3, 2025 09:17
Show Gist options
  • Select an option

  • Save nandakoryaaa/8c7651046010c28e015cc67dac7ca6de to your computer and use it in GitHub Desktop.

Select an option

Save nandakoryaaa/8c7651046010c28e015cc67dac7ca6de to your computer and use it in GitHub Desktop.
A game of guessing 5-letter words (prototype)
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <process.h>
#include <time.h>
#include <string.h>
#define LETTER_CNT 5
typedef enum {
NO_LETTER, HAS_LETTER, OK_LETTER
} LetterStatus;
typedef struct {
LetterStatus status[LETTER_CNT];
size_t ok_cnt;
} WordStatus;
typedef struct {
char letters[LETTER_CNT + 1];
} InputWord;
static const char* words[10] = {
"apple", "haven", "begin", "peach", "rotor",
"spray", "scout", "melon", "grass", "berry"
};
const char* get_random_word(const char** words, size_t word_cnt)
{
size_t rand_index = rand() * (word_cnt - 1) / RAND_MAX;
return words[rand_index];
}
uint32_t get_letter(const char* word, size_t index)
{
return word[index];
}
uint8_t has_letter(const char* word, uint32_t test_letter)
{
for (size_t i = 0; i < LETTER_CNT; i++) {
uint32_t letter = get_letter(word, i);
if (letter == test_letter) {
return 1;
}
}
return 0;
}
WordStatus check_word(const char* word, const char* test_word)
{
WordStatus ws = { .ok_cnt = 0 };
for (size_t i = 0; i < LETTER_CNT; i++) {
uint32_t letter = get_letter(word, i);
uint32_t test_letter = get_letter(test_word, i);
if (letter == test_letter) {
// есть на своём месте
ws.status[i] = OK_LETTER;
ws.ok_cnt++;
} else if (has_letter(word, test_letter)) {
// есть в другом месте
ws.status[i] = HAS_LETTER;
} else {
// нет вообще
ws.status[i] = NO_LETTER;
}
}
return ws;
}
void print_status(WordStatus* ws)
{
const char status_display[3] = { 'x', '-', '+' };
for (size_t i = 0; i < LETTER_CNT; i++) {
printf("%c", status_display[ws->status[i]]);
}
printf("\n");
}
InputWord get_word()
{
InputWord input;
fgets(input.letters, sizeof(input.letters), stdin);
if (input.letters[strlen(input.letters) - 1] != '\n') {
// читать остаток во временный буфер
char buf[100];
do {
fgets(buf, sizeof(buf), stdin);
} while (buf[strlen(buf) - 1] != '\n');
}
return input;
}
int main()
{
srand(time(NULL) ^ getpid());
size_t word_cnt = 10;
InputWord input;
WordStatus ws;
while (1) {
const char* word = get_random_word(words, word_cnt);
for (int try_cnt = 1; try_cnt < 7; try_cnt++) {
printf("try #%u: ", try_cnt);
input = get_word();
ws = check_word(word, input.letters);
printf("%s\n", input.letters);
print_status(&ws);
if (ws.ok_cnt == LETTER_CNT) {
break;
}
}
if (ws.ok_cnt == LETTER_CNT) {
printf("YOU WON!\n");
} else {
printf("YOU LOST!\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment