前段时间,我为 Wordle 问题制作了一个原理证明程序,但在我提交我提议的程序之前,问题/问题就关闭了。以下是示例程序。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include <string.h>
#define MAX_NUM_OF_WORDS 100
bool processGuess(const char* theAnswer, const char* theGuess)
{
//char clue[6] = {'-', '-', '-', '-', '-', '\0'};
char clue[6] = {'/', '/', '/', '/', '/', '\0'}; /* Per the above parameters */
for (int i=0; i<5; i++)
{
for (int j=0; j<5; j++)
{
if ((theGuess[i] == theAnswer[j]) && (i == j)) /* Letter matches in the right spot */
{
//clue[i] = theAnswer[i];
clue[i] = '+'; /* Per the above parameters */
break;
}
if ((theGuess[i] == theAnswer[j]) && (i != j)) /* Letter is in the word but not in the right spot */
{
//clue[i] = theAnswer[j] + 32; /* Display the letter as lower case */
clue[i] = '|'; /* Per the above parameters */
break;
}
}
}
if (strcmp(theAnswer, theGuess) == 0) /* Takes care of any possible display of lower case if a letter is used more than once */
{
printf("%s", theAnswer);
}
else
{
printf("%s\n", clue);
}
return (strcmp(theAnswer, theGuess) == 0);
}
int main()
{
char** wordsList = calloc(MAX_NUM_OF_WORDS, sizeof(char*));
int wordCount = 0;
char* fiveLetterWord = malloc (6*sizeof (char));
FILE* wordsFile = fopen("words.txt", "r");
while (fscanf(wordsFile, "%s", fiveLetterWord) != EOF && wordCount <MAX_NUM_OF_WORDS)
{
wordsList[wordCount] = fiveLetterWord;
wordCount++;
fiveLetterWord = malloc(6*sizeof(char));
}
fclose(wordsFile);
srand(time(NULL));
char* answer = wordsList[rand()%wordCount];
int num_of_guesses = 0;
bool guessed_correctly = false;
char* guess = malloc(6*sizeof(char));
while (num_of_guesses < 6 && !guessed_correctly)
{
printf("\n");
printf("enter a 5 letter word: ");
scanf("%s", guess);
printf("You entered: %s\n", guess);
num_of_guesses += 1;
guessed_correctly = processGuess (answer, guess);
}
if (guessed_correctly)
{
printf("\n");
printf("You guessed the correct word in %d times!\n", num_of_guesses);
}
else
{
printf("\n");
printf("*(No guesses left, The correct word is %s)*\n", answer);
}
for (int i=0; i<wordCount; i++)
{
free(wordsList[i]);
}
free(wordsList);
free(fiveLetterWord);
free(guess);
return 0;
}
该程序从包含五个大写字母的单词的文本文件中读取单词以模仿在线游戏。最初,当输入一个单词时,会进行以下测试:
- 如果单词中未使用字母,则会在单词的该位置放置破折号 ('-')。根据您的规则,这将包含一个正斜杠 ('/')。
- 如果在单词中使用了一个字母,但它位于单词的不同位置,则该字母将在该位置更改为小写。根据您的规则,这将包含一个竖线('|')。
- 如果在单词中和正确的空格中使用了字母,则该字母会在该位置以大写形式出现。根据您的规则,这将包含加号 ('+')。
使用上述参数测试代码,这是终端上的一些示例输出。
@Una:~/C_Programs/Console/Wordle/bin/Release$ ./Wordle
enter a 5 letter word: HELLO
You entered: HELLO
/|///
enter a 5 letter word: ADAGE
You entered: ADAGE
/|/++
enter a 5 letter word: FUDGE
You entered: FUDGE
FUDGE
You guessed the correct word in 3 times!
我猜您必须遵守角色显示的规则,但您可以尝试一下。如果您想尝试它们,我将程序中的原始代码行注释掉。另外,正如我所指出的,此代码是专门为网络游戏等五个字符的单词设置的,但让它接受不同长度的单词应该不难。
试一试,看看这是否能让你在你的项目中前进。