simple simon游戏....(已更改)

由本社区发起的开源项目
回复
hanis_ghost
帖子: 41
注册时间: 2015-06-19 21:16

simple simon游戏....(已更改)

#1

帖子 hanis_ghost » 2016-07-06 19:55

我按照《c语言入门经典》里第四章最后那个例子写了个simple simon 的游戏,就是显示几个数字,一秒后删掉数字,然后让玩家输入,看对不对。
(已成功更改错误)

代码: 全选

#include<stdio.h>
#include<ctype.h>
#include<stdbool.h>  
#include<stdlib.h>
#include<time.h>
int main()
{
//以下都是声明****************************
	char another_game;		//是否开始新游戏
	const int DELAY=1;		//数字显示的时间
	bool correct =true;		//玩家输入是否正确
	time_t seed=0;
	unsigned int tries;		//玩家尝试的次数
	unsigned int number;		//存储玩家输入的数字
	unsigned int digit;		//它用来确定显示几位数
	time_t wait_start;     //存储当前的时间
//以下是游戏开始前的提示语*****************
	printf("simple simon is beginning,are you ready?(click y to begin)\n");
	printf("等会儿数字要一个个输入\n");
	setbuf(stdin,NULL);
	scanf("%c",&another_game);
	if(tolower(another_game)!='y')
		return 0 ;
//以下是游戏的核心部分********************
	do
	{
		tries=0;
		digit=2;
		do
		{
			tries++;
			wait_start=clock();
			srand(time(&seed));
			for(int i=1;i<=digit;i++)
			{
				setbuf(stdout,NULL);
				printf("%d",rand()%10);
			}			//这个for显示数字
		 	for(;clock()-wait_start<DELAY*CLOCKS_PER_SEC;) 
		 		  ;		//持续DELAY秒
			for(int i=1;i<=digit;i++)
				printf("\b");
			for(int i=1;i<=digit;i++)
				printf(" ");
			if(tries==1)
				printf("Now you enter\n");
			srand(seed);									
			for(int i=1;i<=digit;i++)
			{
				setbuf(stdin,NULL);			//linux里要用这个清除缓冲区
				scanf("%u",&number);		//读取玩家输入的数字
				if(number!=rand()%10)
					{
						correct=false;
						break;
					}
				
			}
			if(tries==3)
					{digit++;tries=0;}
			printf("%s\n",correct ? "correct!!" : "wrong!!");
		}
		while(correct==true);
		printf("another new game?(y or N)\n");
		setbuf(stdin,NULL);
		scanf("%c",&another_game);
	}
	while(tolower(another_game)=='y');
}
上次由 hanis_ghost 在 2016-07-08 8:10,总共编辑 1 次。
头像
astolia
论坛版主
帖子: 6386
注册时间: 2008-09-18 13:11

Re: simple simon游戏....(离成功就差一步。。)

#2

帖子 astolia » 2016-07-07 20:06

又是这个基础的问题,每隔一阵子就会换个面貌被不同的人一遍又一遍提出来。
终端作为stdout时默认是行缓冲,没遇到'\n'缓冲区又没满的话数据不会输出到终端上
你可以在代码开头加上以下这句把stdout强制设置成无缓冲模式

代码: 全选

setbuf(stdout,NULL);
也可以用一个外部程序来设置

代码: 全选

stdbuf -o 0 编译出的程序路径
回复