头文件和全局变量
#include<stdio.h>
#include<stdlib.h>// cls清屏 gotoxy自己定义的防闪屏
#include<conio.h>//getch kbhit
#include<windows.h>//sleep
//全局变量
int postion_x,postion_y;//飞机位置
int high, width;//边框位置
int bullet_x, bullet_y;//子弹位置
int enemy_x, enemy_y;//敌机位置
static int score;//击中得分
防闪屏和隐藏光标
void gotoxy(int x, int y) {//光标移动到 x,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 Firstup() {//初始化
high = 24;
width = 34;
postion_x = high / 2;
postion_y = width / 2;
bullet_x = -1;
bullet_y = postion_y;
enemy_x = 1;
enemy_y = postion_y;
score = 0;
HideCursor();
}
显示画面
void show() {//显示画面
gotoxy(0, 0);//防闪屏
int i, j;
for (i = 0; i < high; i++) {//纵坐标
for (j = 0; j < width; j++)//横坐标
{
if (i == postion_x && j == postion_y)//只有在这个位置才会输出飞机
{
printf("*");
}
if (i == postion_x+1 && j == postion_y-1)//只有在这个位置才会输出飞机
{
printf("***");
}
else if (i==bullet_x&&j==bullet_y)//输出子弹
printf("|");
else if (i == enemy_x && j == enemy_y)//输出敌机
printf("@");
else
printf(" ");
}
printf("\n");
}
if (score < 0) {
printf("Game Over\n");
exit(0);
}
else {
printf("得分:%d\n", score);
}
}
人机交互
void FrontInput() {//对于用户
char input;
if (kbhit()) {//如果有按键输入
input = getch();//这两个函数都在conion中
if (input == 's')
postion_x++;
if (input == 'w')
postion_x--;
if (input == 'a')
postion_y--;
if (input == 'd')
postion_y++;
if(input==' ')
bullet_x = postion_x-1;
bullet_y = postion_y;
}
}
后台
void BackInput() {//对于后台
if(bullet_x >-1)//子弹轨迹
bullet_x--;
static int speed = 0;//static 不受函数影响运行完了,依旧有存储空间不会消失,数值也不会归零
//用于控制飞机的下落速度 运行十次才会下路一次
if (speed < 16)
speed++;
if (enemy_x > high) {
enemy_x = 0;
enemy_y = rand() % width;//rand 是随机生成一个数 取余数就是变小在这个游戏框内
}
else {
if (speed == 16) {
enemy_x++;
speed = 0;
}
}
if (enemy_x == bullet_x && enemy_y == bullet_y) {//得分系统
enemy_x = 0;
score++;
enemy_y = rand() % width;
}
if (enemy_x == postion_x && enemy_y == postion_y) {//撞到的话丢分
enemy_x = 0;
score--;
enemy_y= rand() % width;
}
if (enemy_x == postion_x + 1 && enemy_y == postion_y - 1)//同上
{
enemy_x = 0;
score--;
enemy_y = rand() % width;
}
}
主函数
int main() {
Firstup();
while (1) {
show();
FrontInput();
BackInput();
}
return 0;
}
实现: