C語言-簡單的Simon遊戲
阿新 • • 發佈:2018-12-30
遊戲說明:計算機會在螢幕上將一串數字顯示很短的時間。玩家必須在數字消失之前記住他們,然後輸入這串數字。每次過關後,計算機會顯示更長的一串數字,讓玩家繼續玩下去。玩家應儘可能使這個過程重複更多的次數。
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
int main(void){
char another_game = 'Y'; //Records if another game is to be played
const unsigned int DELAY = 1; //Display period in seconds
bool correct = true;
unsigned int tries = 0;
unsigned int digits = 0;
time_t seed = 0;
unsigned int number = 0;
time_t wait_start = 0;
clock_t start_time = 0;
unsigned int score = 0;
unsigned int total_digits = 0 ;
unsigned int game_time = 0;
//how to play the game
printf("To play Simple Simon,"
"watch the screen for a sequence of digits.");
printf("\nWatch carefully,as the digits are only displayed"
"for %u second%s ",DELAY,DELAY>1?"s!":"!");
printf ("\nThe computer will remove them,and then prompt you"
"to enter the same sequence.");
printf("\nWhen you do,you must put spaces between the digits.\n");
printf("\nGood Luck!\nPress Enter to play\n");
scanf("%c",&another_game);
do{
//Initialize game
correct = true;
tries = 0;
digits = 2;
start_time = clock();
//Inner loop continues as long as sequences are entered correctly
while(correct){
++tries;
wait_start = clock();
//Generate a sequence of digits and display them
srand(time(&seed));
for(unsigned int i=1;i<=digits;++i){
printf("%u ",rand() % 10);
}
/*Code to wait one second*/
for(;clock() - wait_start < DELAY*CLOCKS_PER_SEC;);
/*Code to overwrite the digit sequence*/
printf("\r"); //Go to beginning of the line
for(unsigned int i=1;i<=digits;++i)
printf(" "); //Output spaces to cover the number that already printf
if(tries == 1)
printf("\nNow you enter the sequence - don't forget"
"the spaces\n");
else
printf("\r");
/*Code to prompt for the input sequence*/
srand(seed);
for(unsigned int i=1;i<=digits;++i){
//Read the input sequence & check against the original
scanf("%u",&number);//read a digit
if(number != rand()%10){//compare with generater digit
correct = false;
break;
}
}
/*on every third successful try,increase the sequence length*/
if(correct && ((tries%3)==0))
++digits;
printf("%s\n",correct?"Correct!" : "Wrong!");
}
/*output the score when the game is finished*/
score = 10*(digits-((tries%3)==1));//
total_digits = digits*(((tries%3)==0)?3:tries%3);
if(digits>2)
total_digits+=3*((digits-1)*(digits-2)/2 - 1);
game_time = (clock()- start_time)/CLOCKS_PER_SEC - tries*DELAY;
if(total_digits>game_time)
score += 10*(game_time - total_digits);
printf("\n\nGame time was %u seconds.your score is %u",game_time,score);
fflush(stdin);
printf("\nDo you want play again ?");
scanf("%c",&another_game);
}while(toupper(another_game)=='Y');
return 0;
}