用c++写猜单词游戏代码
时间: 2023-06-01 09:02:06 浏览: 84
以下是一个简单的猜单词游戏代码:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#define MAX_WORDS 10 // 最大单词数
#define WORD_LEN 20 // 单词最大长度
char *words[MAX_WORDS] = { // 单词列表
"apple",
"banana",
"orange",
"grape",
"watermelon",
"pineapple",
"peach",
"pear",
"kiwi",
"lemon"
};
int main() {
srand(time(NULL)); // 初始化随机数种子
int n = rand() % MAX_WORDS; // 随机选择一个单词
char *word = words[n];
int len = strlen(word);
char *guess = malloc(len + 1); // 动态分配存储猜测的单词
memset(guess, '_', len); // 初始化猜测单词为下划线
guess[len] = '\0';
int tries = 0; // 猜测次数
int max_tries = 10; // 最大猜测次数
printf("Welcome to the Guess Word game!\n");
printf("The word has %d letters. You have %d tries.\n", len, max_tries);
while (tries < max_tries) {
printf("Guess a letter: ");
char c;
scanf(" %c", &c);
c = tolower(c); // 将输入字母转换为小写字母
int found = 0; // 是否猜对了一个字母
for (int i = 0; i < len; i++) {
if (word[i] == c && guess[i] == '_') {
guess[i] = c;
found = 1;
}
}
if (found) {
printf("Good guess! The word is now: %s\n", guess);
if (strcmp(word, guess) == 0) { // 猜对了整个单词
printf("Congratulations! You guessed the word %s in %d tries.\n", word, tries + 1);
break;
}
} else {
printf("Sorry, %c is not in the word. The word is still: %s\n", c, guess);
tries++;
}
}
if (tries == max_tries) { // 猜测失败
printf("Sorry, you failed to guess the word %s. Better luck next time!\n", word);
}
free(guess); // 释放动态分配的内存
return 0;
}
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)