#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
//全局变量的定义
#define HIGH 20 //游戏界面高度
#define WIDTH 30 // 游戏界面宽度
#define NUM 10 //敌机下落速度
int position_x, position_y; //飞机位置
int bullet_x, bullet_y; //子弹位置
int enemy_x, enemy_y; //敌机位置
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 startup()//数据的初始化
{
//初始化飞机
position_x = HIGH / 2; //高度
position_y = WIDTH / 2; //宽度
//初始化子弹
bullet_x = -1;
bullet_y = position_y;
//初始化敌机
enemy_x = 0;
enemy_y = position_y;
//初始化得分
score = 0;
}
void show()//显示画面
{
//system("cls"); //清屏函数
gotoxy(0, 0); //使光标回到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 == enemy_x && j == enemy_y)//输出敌机
{
printf("@");
}
else
{
printf(" ");
}
}
printf("\n");
}
printf("得分:%d", score);
}
void updateWitoutIput()//与用户输入无关的更新
{
if (bullet_x > -1) //让子弹向上落
{
bullet_x--;
}
if (bullet_x == enemy_x && bullet_y == enemy_y) //命中敌机
{
score++; //得分+1
enemy_x = -1; //生成新的飞机
enemy_y = rand() % WIDTH;
bullet_x = -1; //让子弹直接出现屏幕外,直到下一次发射子弹
}
static int speed = 0; //控制敌机下落速度
if (speed < NUM) //每进行NUM次敌机下落一次
{
speed++;
}
else
{
enemy_x++;
speed = 0;
}
if (enemy_x > HIGH) //敌机一直下落到底部
{
enemy_x = -1;
enemy_y = rand() % WIDTH;
}
}
void updateWithInput()//与用户输入有关的更新
{
//用户输入
char input;
if (_kbhit())
{
input = _getch();
if (input == 'w')
position_x--;
if (input == 's')
position_x++;
if (input == 'a')
position_y--;
if (input == 'd')
position_y++;
if (input == ' ')
{
bullet_x = position_x - 1;
bullet_y = position_y;
}
}
}
int main()
{
startup();//初始化
HideCursor();
srand((unsigned)time(NULL));
while (1)
{
show();//显示画面
updateWitoutIput();//与用户输入无关的更新 //更新数据
updateWithInput(); //与用户输入有关的更新 //输入分析
}
system("pause");
return 0;
}
整个游戏是个二维数组,子弹就你发射之后一直往你发射位置的y轴加加,敌机往下落就是y轴减减