主要目标:
制作一个小游戏,从一开始随机产生4个数字,2s后消失,玩家从终端输入看到的数字,若与所给数据一致,则挑战成功,程序所给数字加一,同样2s后消失,玩家接着猜测,若错误,则游戏结束,以此类推。
主要的技术手段:
产生随机数 2s清屏 for循环 while死循环 if条件语句
产生随机数
方法:rand()函数和srand()函数
rand()函数 | srand()函数 | |
---|---|---|
函数头文件 | <stdlib.h > | <stdlib.h> |
函数定义 | int rand(void) | void srand(unsigned int seed) |
函数功能 | 产生一个随机数 | 设置随机数种子 |
返回值 | 返回0到RAND-MAX之间的随机数值 | |
函数说明 | 通常可以用getpid()(获取当前进程的进程识别码)或者time(NULL)(获取当前系统的时间信息)来充当种子,保持每次运行的种子是不一样的 |
2s清屏
在Windows系统中,导入头文件#include <windows.h>
//延迟2s
Sleep(2000);
//刷新屏幕
system("cls");
while死循环
while(1);
完整代码如下
#include <stdio.h>
#include <stdlib.h>
#include <windows.h> //与sleep相对应的头文件
#include <time.h>//播一个种子
int main(){
int count = 4;//记录每次生成多少个随机数
while(1){//死循环
unsigned int seed = time(NULL);//种子值要一样,方法:将种子记录下来
//设置随机数的种子
srand(seed);
for(int i = 0; i < count; i++){
//生成一个随机数
int temp = rand() % 9 + 1;
printf("%d ",temp);
}
printf("\n");
//延迟2s
Sleep(2000);
//刷新屏幕
system("cls");
int temp;
printf("请输入:");
//重新设种子和之前生成时一样
srand(seed);
//接收用户输入 一个一个接收
for(int i = 0; i<count; i++){
scanf("%d",&temp);
//获取对应的生成的随机数
int old = rand() % 9 + 1;
//比较输入与随机数是否一致
if(temp != old){
printf("错误,退出程序!");
exit(EXIT_SUCCESS);
}
}
count++;
}
return 0;
}