c语言小游戏代码大全
c#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int numberToGuess, playerGuess, attempts = 0;
srand(time(0)); // 设置随机种子
// 生成一个1到100之间的随机数
numberToGuess = rand() % 100 + 1;
printf("欢迎参加猜数字游戏!\n");
printf("我已经选好了一个1到100之间的数字,你来猜猜是多少?\n");
do {
printf("请输入你的猜测:");
scanf("%d", &playerGuess);
attempts++;
if (playerGuess > numberToGuess) {
printf("太大了!\n");
} else if (playerGuess < numberToGuess) {
printf("太小了!\n");
} else {
printf("恭喜你,猜对了!\n");
printf("你一共用了%d次尝试。\n", attempts);
}
} while (playerGuess != numberToGuess);
return 0;
}
你可以根据自己的兴趣和想法扩展这个代码,增加更多的功能和玩法。例如,你可以添加计分系统、难度级别、错误输入处理等功能。
c#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define MAX_WORDS 5
#define MAX_WORD_LENGTH 20
char words[MAX_WORDS][MAX_WORD_LENGTH] = {
"apple",
"banana",
"orange",
"grape",
"melon"
};
int main() {
srand(time(0));
int randomIndex = rand() % MAX_WORDS;
char *wordToGuess = words[randomIndex];
int wordLength = strlen(wordToGuess);
char guessedWord[MAX_WORD_LENGTH];
int attempts = 0;
int i;
// 初始化猜测单词
for (i = 0; i < wordLength; i++) {
guessedWord[i] = '_';
}
guessedWord[i] = 'c#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define MAX_WORDS 5
#define MAX_WORD_LENGTH 20
char words[MAX_WORDS][MAX_WORD_LENGTH] = {
"apple",
"banana",
"orange",
"grape",
"melon"
};
int main() {
srand(time(0));
int randomIndex = rand() % MAX_WORDS;
char *wordToGuess = words[randomIndex];
int wordLength = strlen(wordToGuess);
char guessedWord[MAX_WORD_LENGTH];
int attempts = 0;
int i;
// 初始化猜测单词
for (i = 0; i < wordLength; i++) {
guessedWord[i] = '_';
}
guessedWord[i] = '\0'; // 添加字符串结束符
printf("欢迎参加猜单词游戏!\n");
printf("单词长度为%d个字母。\n", wordLength);
printf("猜一猜这个单词是什么:%s\n", guessedWord);
while (strcmp(wordToGuess, guessedWord) != 0) {
char guess;
printf("请输入你的猜测:");
scanf(" %c", &guess); // 加一个空格用于清除缓冲区的换行符
// 检查猜测是否在单词中
int found = 0;
for (i = 0; i < wordLength; i++) {
if (wordToGuess[i] == guess) {
guessedWord[i] = guess;
found = 1;
}
}
if (found) {
printf("好猜!\n");
} else {
printf("很遗憾,这个字母不在单词中。\n");
}
printf("当前猜测状态:%s\n", guessedWord);
attempts++;
}
printf("恭喜你,你猜对了!\n");
printf("你一共用了%d次尝试。\n", attempts);
return 0;
}
'; // 添加字符串结束符
printf("欢迎参加猜单词游戏!\n");
printf("单词长度为%d个字母。\n", wordLength);
printf("猜一猜这个单词是什么:%s\n", guessedWord);
while (strcmp(wordToGuess, guessedWord) != 0) {
char guess;
printf("请输入你的猜测:");
scanf(" %c", &guess); // 加一个空格用于清除缓冲区的换行符
// 检查猜测是否在单词中
int found = 0;
for (i = 0; i < wordLength; i++) {
if (wordToGuess[i] == guess) {
guessedWord[i] = guess;
found = 1;
}
}
if (found) {
printf("好猜!\n");
} else {
printf("很遗憾,这个字母不在单词中。\n");
}
printf("当前猜测状态:%s\n", guessedWord);
attempts++;
}
printf("恭喜你,你猜对了!\n");
printf("你一共用了%d次尝试。\n", attempts);
return 0;
}
这个代码示例实现了一个简单的猜单词游戏。程序会随机选择一个单词,玩家需要猜测这个单词是什么,每次可以猜测一个字母。程序会提供反馈,告诉玩家他们猜对了多少个字母。游戏会持续直到玩家猜出整个单词为止。
你可以根据需要修改单词列表、调整猜测机制或者添加更多的功能来扩展这个简单的游戏。