大一期末要交個C語言遊戲+答辯,先來個小遊戲練練手
一個簡易的打字遊戲,難得註釋寫的很全,就放上來了
有錯歡迎指出,遊戲有愛自取
C
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#define MAXN 5//數組的大小
#define WIDTH 40//在[0,WIDTH]範圍內生成字母
#define HIGH 20//垂直下降的高度
int grade,tier=1,hp=3;//分數,等級和生命值
int gameover=0;
struct ALPHA{
int x;
int y;
char ch;
int alive=0; //用來記錄該元素是否存在,和judge()函數一起理解
}alpha[MAXN];
void HideCursor(void)//隱藏光標
{
CONSOLE_CURSOR_INFO Cursor_info={1,0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&Cursor_info);
}
void gotoxy(int x,int y)
{
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos={x,y};
SetConsoleCursorPosition(handle,pos);
}
void init(void)//隱藏指針和初始化隨機數
{
HideCursor();
srand((unsigned)time(0));
}
void judge(void)//判斷是否需要產生新的字母
{
if(hp==0)//生命爲0,遊戲結束
{
gotoxy(0,HIGH+4);
printf("gameover\n");
system("pause");
exit(0);
}
int i,count; //count用來記錄已經擁有的字母,遊戲採取count==tier
for(i=0,count=0;i<MAXN;i++)
if(alpha[i].alive)
count++;
while(count<tier)//保證同時在屏幕上出現的字母數等於難度
{
for(i=0;i<MAXN;i++)
{
if(!alpha[i].alive)
{
alpha[i].x=rand()%WIDTH;
alpha[i].y=-1;
alpha[i].ch=rand()%26+'A';
alpha[i].alive=1;
count++;
break;
}
}
}
if(tier==1&&grade==5)//根據分數增加難度
tier++;
else if(tier==2&&grade==10)
tier++;
else if(tier==3&&grade==15)
tier++;
else if(tier==4&&grade==20)
tier++;
for(i=0;i<MAXN;i++)//如果字母落到底,清除這個字母,生命值減一
if(alpha[i].alive)
if(alpha[i].y==HIGH)
{
hp--;
alpha[i].alive=0;
}
}
void show(void)//實現從上往下落字母的效果
{
int i;
switch(tier)//根據難度指定字母下落的速度
{
case 1:
Sleep(500);
break;
case 2:
Sleep(400);
break;
case 3:
Sleep(300);
break;
case 4:
Sleep(200);
break;
case 5:
Sleep(100);
break;
}
for(i=0;i<MAXN;i++)//打印字母
{
if(alpha[i].alive)
{
if(alpha[i].y!=-1)//要保證gotoxy()的y爲有效值
{
gotoxy(alpha[i].x,alpha[i].y);
putchar(' ');
}
alpha[i].y++;
gotoxy(alpha[i].x,alpha[i].y);
putchar(alpha[i].ch);
}
}
gotoxy(0,HIGH);
for(int i=0;i<WIDTH;i++)//打印邊界以及統計信息
putchar('-');
printf("\n等級:%d\n",tier);
printf("分數:%d\n",grade);
printf("生命值%d\n",hp);
}
void get_input(void)//讀取玩家輸入
{
int i;
char input;
if(_kbhit())
{
input=_getch();
input=_toupper(input);
for(i=0;i<MAXN;i++)
if(alpha[i].alive)
if(alpha[i].ch==input)
{
gotoxy(alpha[i].x,alpha[i].y);
putchar(' ');
alpha[i].alive=0;
grade++;
}
}
}
void start(void)
{
init();
while(1)
{
judge();
show();
get_input();
}
}
int main(void)
{
start();
return 0;
}