比较简单的飞机小游戏,直接用C语言即可实现功能,我已经做了较为完整的注释,希望大家可以看得懂,对学C的有所帮助。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h> //用于抓去键盘输入
#include <Windows.h>
//函数外得定义一些全局变量,
int position_x,position_y;//飞机的定位
int high,width;//游戏画面的尺寸
int bullet_x,bullet_y; //子弹的定位
int enem_x,enem_y; //敌机
int score ; //得分
//必须写足够的注释
// 光标闪烁清除
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info = {1 , 0}; //第二个值为0表示隐藏光标
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
}
void init()
{
high = 20;
width = 30;
position_x = high/2;
position_y = width/2;
bullet_x = 0;
bullet_y = position_y;
enem_x = 0;
enem_y = 2;
score =0;
HideCursor();
}
// 清屏程序
void gotoxy(int x,int y) //光标移动到xy的位置
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X=x;
pos.Y=y;
SetConsoleCursorPosition(handle,pos);
}
void show()
{
// "cls"清屏速度太快,以至于会闪烁。
//system("cls"); //清屏
//调用 函数gotoxy。不会刷屏太快。
gotoxy(0,0);
int i,j; //空格位置
for(i=0;i<high;i++)
{
for(j=0;j<width;j++)
{
if((i == position_x) && (j == position_y))
printf("*"); //飞机位置
else if ((i == bullet_x) && (j == bullet_y))
printf("|"); //子弹的飞出
else if((i == enem_x) && (j == enem_y))
printf("@"); //敌机
else
printf(" "); //其余位置为空格
}
printf("\n");
}
printf("得分:%d",score);
}
void updateWithInput() //用户输入
{
char input;
if(kbhit()) //检测按键是否有效
{
input = getch();
if(input == 'a')
position_y--;
if(input == 'w')
position_x--;
if(input == 'd')
position_y++;
if(input == 's')
position_x++;
if(input ==' ')
{
bullet_x = position_x -1;
bullet_y = position_y;
}
}
}
void updateWithoutInput() //用户输入无关
{
if((bullet_x == enem_x) && (bullet_y == enem_y))
{
score ++; //击中得分
bullet_x = -1; // 子弹消失
enem_x =0; // 敌机重新出现
enem_y = rand() % width; // 敌机位置随机生成,对宽度取余,会在宽度内。
}
if(position_x > high)
{
position_x = high-1;
}
if(position_x < 0)
{
position_x = 0;
}
if(position_y > width)
{
position_y = width-1;
}
if(position_y < 0)
{
position_y = 0;
}
if( bullet_x > -1) //子弹发射,到顶消失
bullet_x--;
static int speed = 0; //控制飞机的速度 ,变量
if(speed < 20) //循环20次,飞机下落一格
speed ++ ;
if(speed ==20)
{
if(enem_x > high)
{
enem_x = 0; //敌机消失后,重新生成
enem_y = rand() % width; // 敌机位置随机生成,对宽度取余,会在宽度内。
}
else
{
enem_x++; //敌机向下落
speed = 0;
}
}
}
int main()
{
init(); //数据初始化
while(1)
{
show(); //显示画面
updateWithoutInput(); //以用户输入无关的更新
updateWithInput(); //与用户输入有关的
}
return 0;
}