C语言游戏开发——打飞机游戏2.0
本次打飞机游戏对上次的打飞机游戏2.0做了代码重构和升级
通过定义函数来实现多个功能
以下为代码主体
通过w a s d来控制飞机的移动
通过空格来发射子弹
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<Windows.h>
int po_x, po_y;
int bu_x, bu_y;
int high, width;
int enemy_x, enemy_y;
int score;
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info = { 1,0 };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void startup() //数据初始化
{
high = 20;
width = 30;
po_x = high / 2;
po_y = width / 2;
bu_x = 0;
bu_y = po_y;
enemy_x = 0;
enemy_y = po_y;
score = 0;
}
void gotoxy(int x,int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
void show() //显示画面
{
gotoxy(0, 0);
system("cls");
int i,j;
for (i = 0; i < high; i++)
{
for (j=0; j< width;j++)
{
if ((i == po_x) && (j == po_y))
{
printf("*"); //输出飞机*s
}
else if ((i==enemy_x)&&(j==enemy_y))
{
printf("@"); //输出敌人@
}
else if ((i == bu_x) && (j == bu_y))
{
printf("|"); //输出子弹|
}
else
{
printf(" "); //输出空格
}
}
printf("\n");
}
}
void updateWithoutInput()
{
if (bu_x > -1)
bu_x--;
if ((bu_x==enemy_x)&&(bu_y==enemy_y))
{
score++; //分数加一
enemy_x=-1; //产生新的敌机
enemy_y=rand()%width;
bu_x=-2; //子弹无效
}
if (enemy_x > high)
{
enemy_x = -1; //产生新的敌机
enemy_y = rand() % width;
}
static int speed = 0;
if (speed<10)
{
speed++;
}
if (speed==10)
{
enemy_x++;
speed = 0;
}
}
void updateWithInput()
{
char input;
if (_kbhit()) //判断是否有输入
{
input = _getch();
if (input == 'a')
po_y--;
if (input == 'd')
po_y++;
if (input == 'w')
po_x--;
if (input == 's')
po_x++;
if (input==' ')
{
bu_x = po_x - 1;
bu_y = po_y;
}
}
}
int main()
{
startup();
HideCursor();
while (1)
{
show();
updateWithoutInput();
updateWithInput();
}
return 0;
}