Simple Simon
用C語言寫一款簡單的西蒙游戲
Simple Simon是一款記憶測驗游戲,計算機在螢屏上短時間顯示一系列數字,當你從螢屏上記住數字的序列時,你必須完全記住這些數字,每次你成功了,你可以重復這個程序,得到一個更長的數字串列供你嘗試,
程式必須生成一個介于0和9之間的整數序列,并在螢屏上顯示該序列一秒鐘,然后再將其洗掉,然后玩家必須嘗試輸入相同的數字序列,序列逐漸變長,直到玩家得到錯誤的序列,然后根據成功嘗試的次數和花費的時間計算得分,然后詢問玩家是否愿意再次玩,
序列長度從3開始,每三次成功嘗試,增加序列長度,
(長度加1)
Simple Simon程式的基本邏輯如下:

編程中將使用以下頭檔案:
#include <stdio.h> /* For input and output */
#include <ctype.h> /* For toupper() function */
#include <stdlib.h> /* For rand() and srand() */
#include <time.h> /* For time() , clock() and CLOCKS_PER_SEC*/
提示:
(1) 等一秒鐘
庫函式clock()回傳自程式啟動以來的時間,以時鐘刻度為單位,頭檔案的<time.h>定義了一個符號CLOCKS_PER_SEC,它是一秒鐘內的時鐘周期數,使用變數now存盤當前時間,回圈的代碼如下:
/* Wait one second */
now = clock();
for( ;clock() - now < CLOCKS_PER_SEC; );
(2) 計算游戲分數
計算玩游戲的總時間(秒):
time_taken = (clock() – startTime) / CLOCKS_PER_SEC;
如果變數計數器存盤成功嘗試的次數,則可以使用以下公式計算游戲分數:
scores = counter * 100 / time_taken
(3) 生成0到9之間的整數序列并在螢屏上顯示該序列
seed = time(NULL);
srand((unsigned int)seed); /* Initialize the random sequence */
for(int i = 0; i < sequence_length; i++)
printf("%2d", rand() % 10);
如果使用相同的種子生成整數序列(srand(seed)),它將生成相同的序列,
(4) 清除輸出的數字序列
printf("\r"); /* go to beginning of the line */
for(int i = 1; i <= sequence_length; i++)
printf(" ");
以下為整個程式源代碼:
/*
Name:programme3.c
Author:祁麟
Copyright:BJTU | school of software
Date:2020/10/27
Description:Write a game of Simple Simon in C.
*/
#include <stdio.h> /* For input and output */
#include <ctype.h> /* For toupper() function */
#include <stdlib.h> /* For rand() and srand() */
#include <time.h> /* For time() , clock() and CLOCKS_PER_SEC*/
#include <stdbool.h>
int main(){
//初始化程式
char another_game = 'N';
bool correct = true;
int counter = 0;
int sequence_length = 0;
time_t seed = 0;
time_t now = 0;
int number = 0;
int time_taken = 0;
int c,i;
do{//初始化游戲回圈
printf("Simon游戲開始!\n");
counter = 0;
sequence_length = 2;
time_taken = clock();
correct = true;
while(correct){
sequence_length += (counter++%3 ==0);
//生成亂數
seed = time(NULL);
now = clock();
srand((unsigned int)seed);
for( i = 1; i <= sequence_length; i++) {
printf("%d ",rand()%10);
}
//等待一秒
for(;clock() - now < CLOCKS_PER_SEC;)
//洗掉數字序列
printf("\r");
for( i = 1; i <= sequence_length; i++){
printf(" ");
}
if(counter == 1){
printf("\n輸入序列,用空格間隔,\n");
} else{
printf("\r");
}
//讀取用戶輸入
//判斷輸入是否正確
srand((unsigned int)seed);
for( i = 1; i<= sequence_length; i++){
scanf("%d",&number);
if(number != rand()%10){
correct = false;
break;
}
}
printf("%s\n",correct?"Correct~":"Wrong!");
}
//結算分數
time_taken = (clock() - time_taken)/CLOCKS_PER_SEC;
printf("您的得分為:%d",--counter*counter*100/time_taken);
while ((c = getchar()) != '\n' );
//是否開始新游戲?
printf("\n是否開始新游戲?(y/n)\n");
scanf("%c",&another_game);
}
while(toupper(another_game) == 'Y');
//結束
return 0;
}
運行截圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/246233.html
標籤:其他
上一篇:Python寫游戲,我上我也行 - Flappy Bird 03
下一篇:湘潭大學通信原理期末簡答題
