C_飞机大战(flappy bird)

头文件和全局变量

#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;
}

实现:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值