1. 程式人生 > >C語言實現簡單的記憶力測試遊戲

C語言實現簡單的記憶力測試遊戲

一個簡單的記憶測試遊戲!
printf("\n記住螢幕上出現的一串數.請仔細看,數字只出現一定時間.");
printf("\n之後數字會消失,你要輸入相同的數字.\n");

printf("\n祝你好運!\n\n是否要開始遊戲(是-Y,否-N)

猜數成功後,難度會上升~~~

#include <stdio.h>
#include <ctype.h>		//使用toupper()函式
#include <time.h>		//time()函式
#include <stdlib.h>		//生成隨機數,rand()和srand()函式
#include <math.h>		//pow()函式

int main(void)
{
	char continue_game = 'Y';			//下一個遊戲
    long int show_time = 1L;			//數字串顯示時間(s)
	int correct = 1;					//判斷使用者輸入的數字是否正確,1-正確,0-錯誤
	unsigned int tries = 0;				//使用者成功次數
	unsigned int digits = 0;			//系統生成的數字串長度
	time_t seed = 0;					//種子值
	time_t wait_time = 0;				//儲存當前時間
	unsigned int score = 0;				//遊戲分數
	clock_t game_start_time = 0;		//遊戲開始時的時間
	unsigned int input_time = 0;		//使用者輸入數字所用的時間
	unsigned int game_end_time = 0;		//遊戲結束時的時間
	long int number = 0L;				//使用者輸入的數字
	unsigned int i = 0;					//迭代器	

	/*描述如何遊戲*/
	printf("\n玩一個簡單的記憶測試遊戲!");
	printf("\n記住螢幕上出現的一串數.請仔細看,數字只出現一定時間.");
	printf("\n之後數字會消失,你要輸入相同的數字.\n");
	printf("\n祝你好運!\n\n是否要開始遊戲(是-Y,否-N):");
	scanf("%c",&continue_game);

	/*一次迴圈即是一次完整的遊戲*/
	while(toupper(continue_game) == 'Y')
	{
		//初始化遊戲
		digits = 2;								//數字串最初長度
		correct = 1;
		tries = 0;								//成功次數
		game_start_time = clock();				//記錄遊戲開始時的時間
		printf("\n遊戲開始!\n");
		while(correct)
		{
			tries++;
			wait_time = clock();				//記錄數字串產生的時間
			srand(time(&seed));					//產生數字串
			for(i = 1; i <= digits; i++)
		    	printf("%u ", rand() % 10);		//顯示隨機數字串

			for( ;clock() - wait_time < show_time * CLOCKS_PER_SEC;); //讓數字串顯示一定時間
			printf("\r");
			for(i = 1; i <= digits; i++)
				printf("  ");					//刪除產生的數字串
			if(1 == tries)
				printf("\n現在輸入數字(不要忘記空格)\n");
			else
		    	printf("\r");					//返回到當前行行首
			srand(seed);						//再次產生上次的數字串
			for(i = 1; i <= digits; i++)
			{

				scanf(" %ld",&number);			//使用者輸入數字
				if(number != rand() % 10)
				{
					correct = 0;
					break;			//輸入錯誤,結束遊戲
				}
				getchar();

			}
			if(correct && ((tries % 3) == 0))	//成功且滿三次,隨機數字串長度增加一位
			{
				digits++;
				if(0 == (digits % 5))			//數字串是5的倍數時,顯示時間加一秒
			    	show_time++;
			}
			printf("%s\n",correct == 1 ? "正確!" : "錯誤!");
		}

		/*百分制計分並顯示分數*/
		score = 10 * (digits - (1 == (tries % 3)));
		input_time = digits * ((0 == (tries % 3)) ? 3 : tries % 3);
		if(digits > 2)
			input_time += 3 * ((digits - 1) * (digits - 2) / 2 -1);
		game_end_time = (clock() - game_start_time) / CLOCKS_PER_SEC - tries * show_time;
		if(input_time > game_end_time)
			score += 10 * (game_end_time - input_time);
		printf("\n\n遊戲時間是%u秒.你的分數是%u",game_end_time,score);
		fflush(stdin);		//清空鍵盤輸入緩衝區

		/*是否繼續遊戲*/
		printf("\n你想要繼續進行遊戲嗎?(Y/N)?\n請輸入: ");
		scanf("%c",&continue_game);
	}
	printf("\n謝謝使用!\n");
	return 0;
}

執行後如圖所示: