以下是一个简单的C语言打字游戏代码示例。在这个游戏中,程序会随机生成一个单词,用户需要在规定的时间内输入这个单词。如果用户成功输入,游戏继续;如果失败,游戏结束。 #include #include #include #include #include #define WORD_LEN 10 #define MAX_TRIES 3 void generateWord(char *word) { const char *alphabet = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < WORD_LEN; ++i) { word[i] = alphabet[rand() % (strlen(alphabet))]; } word[WORD_LEN] = '\0'; } int main() { srand(time(NULL)); // 初始化随机数种子 char secretWord[WORD_LEN + 1]; char userInput[WORD_LEN + 1]; int tries = 0; generateWord(secretWord); printf("Welcome to the Typing Game!\n"); printf("Try to guess the secret word in %d tries.\n", MAX_TRIES); while (tries < MAX_TRIES) { printf("Attempt %d: ", tries + 1); scanf("%s", userInput); if (strcmp(secretWord, userInput) == 0) { printf("Congratulations! You guessed the word!\n"); return 0; } else { printf("Incorrect. Try again.\n"); tries++; } // 等待一段时间,模拟打字游戏的节奏 usleep(1000000); // 等待1秒 (1000000微秒) } printf("Sorry, you failed to guess the word. The secret word was '%s'.\n", secretWord); return 1; }