[C] 简单的C语言打字游戏代码 →→→→→进入此内容的聊天室

来自 Crimson Kitten, 2024-03-06, 写在 C, 查看 12 次.
URL http://www.code666.cn/view/b0779596
  1. 以下是一个简单的C语言打字游戏代码示例。在这个游戏中,程序会随机生成一个单词,用户需要在规定的时间内输入这个单词。如果用户成功输入,游戏继续;如果失败,游戏结束。
  2.  
  3.  
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <time.h>
  8. #include <string.h>
  9. #include <unistd.h>
  10.  
  11. #define WORD_LEN 10
  12. #define MAX_TRIES 3
  13.  
  14. void generateWord(char *word) {
  15.     const char *alphabet = "abcdefghijklmnopqrstuvwxyz";
  16.     for (int i = 0; i < WORD_LEN; ++i) {
  17.         word[i] = alphabet[rand() % (strlen(alphabet))];
  18.     }
  19.     word[WORD_LEN] = '\0';
  20. }
  21.  
  22. int main() {
  23.     srand(time(NULL)); // 初始化随机数种子
  24.  
  25.     char secretWord[WORD_LEN + 1];
  26.     char userInput[WORD_LEN + 1];
  27.     int tries = 0;
  28.  
  29.     generateWord(secretWord);
  30.  
  31.     printf("Welcome to the Typing Game!\n");
  32.     printf("Try to guess the secret word in %d tries.\n", MAX_TRIES);
  33.  
  34.     while (tries < MAX_TRIES) {
  35.         printf("Attempt %d: ", tries + 1);
  36.         scanf("%s", userInput);
  37.  
  38.         if (strcmp(secretWord, userInput) == 0) {
  39.             printf("Congratulations! You guessed the word!\n");
  40.             return 0;
  41.         } else {
  42.             printf("Incorrect. Try again.\n");
  43.             tries++;
  44.         }
  45.  
  46.         // 等待一段时间,模拟打字游戏的节奏
  47.         usleep(1000000); // 等待1秒 (1000000微秒)
  48.     }
  49.  
  50.     printf("Sorry, you failed to guess the word. The secret word was '%s'.\n", secretWord);
  51.     return 1;
  52. }
  53.  
  54.  
  55.  

回复 "简单的C语言打字游戏代码"

这儿你可以回复上面这条便签

captcha