推荐书籍:《C语言课程设计与游戏开发实践教程》 作者:童晶
项目内容:飞机大战(版本1.0)
主要功能:可暂停游戏、发射炮弹、统计得分等等
# include <stdio.h>
# include <time.h>
# include <stdlib.h>
# include <conio.h>
# include <windows.h>
/*
不足之处:如果敌机被打掉之后,有可能会需要迭代循环后才会重新下落,没有办法重新生成后立刻下落,后续会继续改进优化(因为实现了敌机随分数上升而速度加快的功能,代码会有一定冲突)
*/
//声明全局数据
int high, width;
int position_x, position_y;
int enemy_x, enemy_y;
int bullet_x, bullet_y;
int score;
static int speed;
static int enemy_level;
//清屏函数
void gotoxy(int x, int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
//隐藏光标函数
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
//数据初始化
void startup()
{
HideCursor();
srand((unsigned)time(NULL));
high = 20;
width = 30;
position_x = width / 2;
position_y = high / 2;
enemy_x = rand() % (width - 2) + 3;
enemy_level = 20;
}
//画面展示
void show()
{
gotoxy(0, 0);
int i, j;
for (i = 0; i < high; i++)
{
for (j = 0; j < width; j++)
{
if (i == position_y && j == position_x)
printf("*");
else if (i == bullet_y && j == bullet_x)
printf("|");
else if (i == enemy_y && j == enemy_x)
printf("@");
else
printf(" ");
}
printf("\n");
}
//输出得分
printf("得分:%d\n", score);
}
//与用户输入无关的更新
void updateWithoutInput()
{
//防止战机超出边界
if (position_x <= 0)
position_x = 0;
if (position_x >= width-1)
position_x = width-1;
if (position_y <= 0)
position_y = 0;
if (position_y >= high-1)
position_y = high-1;
//控制敌机下落速度的循环
if (speed < enemy_level)
speed++;
//根据敌机等级调整敌机下落速度
if (score == 5)
enemy_level = 15;
else if (score == 10)
enemy_level = 10;
else if (score == 15)
enemy_level = 6;
int bullet_exit = 1;
//子弹与敌机碰撞
if (bullet_x == enemy_x && bullet_y == enemy_y)//敌机与子弹碰撞
{
enemy_x = rand() % (width - 2) + 3;
enemy_y = 0;
score++;
bullet_exit = 0;
}
else if (enemy_y > high)//敌机超出边界
{
enemy_x = rand() % (width - 2) + 3;
enemy_y = 0;
}
else if (enemy_x == position_x && enemy_y == position_y)//敌机与战机碰撞
{
printf("您的战机坠毁!");
if (score >= 5)//扣分
score -= 5;
else
score = 0;
system("pause");
enemy_x = rand() % (width - 2) + 3;
enemy_y = 0;
}
else
{
if (speed >= enemy_level)
{
enemy_y++;
speed = 0;
}
}
//如果子弹没有击中敌机,那么自由下落
if (bullet_y > -1 && bullet_exit)
bullet_y--;
}
//与用户输入有关的更新
void updateWithInput()
{
char input;
if (_kbhit())
{
input = _getch();
if (input == 'w')
position_y--;
if (input == 's')
position_y++;
if (input == 'a')
position_x--;
if (input == 'd')
position_x++;
if (input == ' ')//按空格发射炮弹
{
bullet_x = position_x;
bullet_y = position_y - 1;
}
if (input == 27)
system("pause");
}
}
int main()
{
startup();
while (1)
{
show();
updateWithoutInput();
updateWithInput();
}
return 0;
}