这段代码实现了一个简单的C语言疯狂打字游戏,它从预设的单词列表中随机选取一个单词,打乱其字母顺序,并要求玩家输入正确单词。代码中使用了srand()函数和time.h头文件来生成随机数,strcpy_s()函数来复制字符串,strlen()函数来获取字符串长度,scanf_s()函数来接收用户输入,strcmp()函数来比较字符串。

然而,代码中存在一些错误,需要进行修正和优化:

  1. 在使用srand()函数之前,应该在头文件中包含time.h,以确保函数可以正常使用。

  2. scanf_s()函数的使用可能导致错误,建议将其改为scanf('%s', &input);。

  3. 代码中没有对用户输入的长度进行检查,可能会导致缓冲区溢出。

  4. 可以考虑添加游戏难度调节功能,例如调整单词难度或游戏时间限制。

  5. 可以添加游戏界面和音效,提升游戏体验。

以下是对代码进行优化后的版本:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
#define MAX_WORDS 10
#define MAX_WORD_LENGTH 50
char words[MAX_WORDS][MAX_WORD_LENGTH] = {
    'apple',
    'banana',
    'orange',
    'watermelon',
    'strawberry',
    'pineapple',
    'grapefruit',
    'kiwi',
    'blueberry',
    'mango'
};
int main() {
    srand(time(0));
    printf('欢迎来到疯狂打字游戏!\n');
    printf('你将会看到一系列乱序的字母,你需要输入对应的正确单词。\n');
    printf('输入'exit'可以退出游戏。\n');

    int score = 0;
    int round = 1;
    while (1) {
        printf('\n第 %d 轮:\n', round);
        // 随机选择一个单词
        int randomIndex = rand() % MAX_WORDS;
        char word[MAX_WORD_LENGTH];
        strcpy_s(word, words[randomIndex]);
        // 乱序字母
        int wordLength = strlen(word);
        for (int i = 0; i < wordLength; i++) {
            int randomIndex = rand() % wordLength;
            char temp = word[i];
            word[i] = word[randomIndex];
            word[randomIndex] = temp;
        }
        // 显示乱序字母
        printf('乱序字母:%s\n', word);
        // 接受用户输入
        char input[MAX_WORD_LENGTH];
        printf('请输入单词:');
        scanf('%s', input);
        // 检查退出条件
        if (strcmp(input, 'exit') == 0) {
            break;
        }
        // 检查答案
        if (strcmp(input, words[randomIndex]) == 0) {
            printf('回答正确!\n');
            score += 10;
        } else {
            printf('回答错误!正确答案是:%s\n', words[randomIndex]);
        }
        round++;
    }
    printf('\n游戏结束!你的得分是:%d\n', score);
    return 0;
}

通过对代码进行优化,可以使游戏更加稳定,并提升游戏体验。


原文地址: https://www.cveoy.top/t/topic/pKIH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录